Foundations
Hello, Numbers!
You're helping a friend split a restaurant bill. The total is $47.50 and there are 4 people. You need to calculate each person's share: 47.50 / 4 = 11.875, round to $11.88.
Print a single number
The simplest thing we can do - tell the computer to show us a number.
number.py
Replay: real traced execution (multi-file project)
print(42)
print(100)
print(-7)
print(42)
1print(42)2print(100)3print(-7)output42 100 -7
The computer echoes back exactly what we ask for.
print
In Python, `print(...)` displays the value to the screen.
Basic arithmetic
Now let's do some math. We can add, subtract, multiply, and divide.
arithmetic.py
Replay: real traced execution (multi-file project)
print(10 + 5)
print(10 - 5)
print(10 * 5)
print(10 / 5)
print(10 % 3)
print(10 + 5)
1print(10 + 5)2print(10 - 5)3print(10 * 5)4print(10 / 5)5print(10 % 3)output15 5 50 2.0 1
operators
Arithmetic operators: `+` add, `-` subtract, `*` multiply, `/` divide, `%` remainder, `//` integer division.
Grouping with parentheses
What if we want to control the order of operations? Use parentheses.
grouping.py
Replay: real traced execution (multi-file project)
print(2 + 3 * 4)
print((2 + 3) * 4)
print(100 / (5 + 5))
print(2 + 3 * 4)
1print(2 + 3 * 4)2print((2 + 3) * 4)3print(100 / (5 + 5))output14 20 10.0
Without parentheses: 2 + 3 * 4 gives 14 (multiply first).
With parentheses: (2 + 3) * 4 gives 20 (add first).
precedence
Multiplication and division happen before addition and subtraction, unless you use parentheses.
A real calculation
Let's calculate the area of a rectangle with sides 7 and 5.
area.py
Replay: real traced execution (multi-file project)
width = 7
height = 5
print(width * height)
width = 3
height = 5
print(width * height)
width = 10
height = 5
print(width * height)
width = 7
height = 4
print(width * height)
width = 7
height = 8
print(width * height)
width ← 7, height ← 5
1width→ 7 = 7 #@width=3, 102height→ 5 = 5 #@height=4, 83print(width7 * height5)output35
width ← 3, height ← 5
1width→ 3 = 32height→ 5 = 53print(width3 * height5)output15
width ← 10, height ← 5
1width→ 10 = 102height→ 5 = 53print(width10 * height5)output50
width ← 7, height ← 4
1width→ 7 = 72height→ 4 = 43print(width7 * height4)output28
width ← 7, height ← 8
1width→ 7 = 72height→ 8 = 83print(width7 * height8)output56
Complex expression
Combine everything: multiple operations, nested parentheses.
complex.py
Replay: real traced execution (multi-file project)
print((10 + 20) * (30 - 15) / 5)
print(((2 + 3) * (4 + 5)) - 10)
print(100 / 10 / 2)
print((10 + 20) * (30 - 15) / 5)
1print((10 + 20) * (30 - 15) / 5)2print(((2 + 3) * (4 + 5)) - 10)3print(100 / 10 / 2)output90.0 35 5.0
The computer follows the same math rules you learned in school.