Python programs run through a set of internal steps that convert human-readable code into instructions the machine can understand.
- Source code is not executed directly by the machine.
- Python processes the code internally before execution.
- This process allows the system to interpret and run programs correctly.
Example:
a = 10
b = 10
print("Sum:", (a+b))
Output:
Sum: 20
Consider this code is saved in a file named first.py.
Execution of a Python Program
During the execution of first.py, Python performs two main steps:
Step 1: Compilation to Bytecode
Python first checks your code for syntax errors. If the code is valid, it is converted into bytecode.
- Bytecode is an intermediate, platform-independent format
- It is not machine code
- It represents instructions like calculations, comparisons, and memory operations
This bytecode is stored in a .pyc file inside a folder named __pycache__.
__pycache__/first.cpython-38.py
Python handles this process automatically, so you usually don’t need to create .pyc files manually.
Step 2: Execution by Python Virtual Machine (PVM)
The Python Virtual Machine (PVM) reads the bytecode and executes it.
- PVM understands the operating system and processor
- It converts bytecode into machine-level instructions
- These instructions are then executed by the CPU
This is why Python works on different platforms without changing the code.