Python runs on an interactive interpreter, which means that you can execute code right away, you don’t have to compile your code before you can run it.
How exactly does this work? The compiler exists to translate the code that we write into machine readable code so the computer can execute it and perform the programmed task.
So how can you execute code in Python without translating it to machine language first?
That’s an excellent question. I did some research to learn more about this, as it has to do with some fundamental concepts involving programming languages.
Python is an “interpretive” programming language. This contrasts with the more conventional “compiled” languages such as C++. Compiled languages require you to write your code, and then compile it into machine-specific binary in an executable file (i.e. .exe on a Windows device). You then run the executable file to run the program.
Python on the other hand, as an interpretive programming language is executed line-by-line by an interpreter at runtime, without prior compilation to machine code. The interpreter in essence, replaces the role of the compiler. You still have to get the code into a form that the machine itself can understand and run, but it happens differently than the more traditional compiling.
Python uses a two-step process that blends compilation and interpretation.
Step 1: When you run a Python script (e.g., script.py), the Python compiler (notice compiling still takes place??) first translates your code into an intermediate form called bytecode (stored in .pyc files). This bytecode is a low-level, platform-independent representation of your code.
Step 2: The Python Virtual Machine (PVM), which is Python’s runtime engine, reads the bytecode and executes it line-by-line. The PVM is not a physical machine but a software layer that interprets bytecode into machine instructions for the CPU.
So as you can see, compilation still takes place, but not in the traditional sense. Unlike C++, Python automates the compilation process because the interpreter handles compilation behind the scenes.