What Python Executes
Unit ID: M01-U01 Estimated active time: 15-20 minutes
The path from code to result
Consider this line:
2 + 3
The line is source code: instructions written in a form Python can read. When you run it, a Python interpreter processes the code. The expression 2 + 3 produces the value 5. A notebook normally displays that value as output.
We can describe the path like this:
- You write source code.
- Python reads and executes it.
- The code produces a value or performs an action.
- The notebook may display output.
The notebook is the workspace around Python. It holds cells, sends code to a Python kernel, and displays results. The notebook is not the Python language itself.
Expressions and actions
An expression produces a value.
10 * 4
The value is 40.
Some code performs an action. The print() function asks Python to display text.
print("Welcome to Python")
Output:
Welcome to Python
The quotation marks tell Python where the text begins and ends. They are not shown in the printed output.
Predict before you run
Look at this code without running it:
6 + 4 * 2
Which result do you expect: 20 or 14?
Python follows the usual arithmetic order. Multiplication happens before addition, so the result is 14.
Now use parentheses:
(6 + 4) * 2
The result is 20. Parentheses make the intended order visible. Clear code is more important than showing how much syntax you know.
A value may exist without being displayed
In a notebook, the last expression in a cell is usually displayed:
12 / 3
But a script does not automatically display every value. print() makes the output request explicit:
print(12 / 3)
Both calculate 4.0. The second also tells Python to display it.
Notice the decimal point. In Python, / produces a floating-point number, even when the mathematical result is a whole number. We will study number types in Module 2.
Try this
Predict each result, then run the code.
7 - 2
3 * 5
8 / 2
print("AI" + " practice")
Expected results:
5
15
4.0
AI practice
Change one number and one piece of text. Run the code again. Explain which part was source code, which value Python produced, and what appeared as output.
Check your understanding
Which statement is most accurate?
- A notebook and Python are exactly the same thing.
- Python executes code; the notebook organises cells and displays the interaction.
- Output is the code before Python reads it.
The second statement is correct.
Takeaway
Code is the instruction. Python executes it. An expression produces a value, and print() makes display explicit. Next, we will see how notebook cells send code to a running Python kernel.
