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
print(42)
print(100)
print(-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
print(10 + 5)
print(10 - 5)
print(10 * 5)
print(10 / 5)
print(10 % 3)
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
print(2 + 3 * 4)
print((2 + 3) * 4)
print(100 / (5 + 5))
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
print(7 * 5)
Complex expression
Combine everything: multiple operations, nested parentheses.
complex.py
print((10 + 20) * (30 - 15) / 5)
print(((2 + 3) * (4 + 5)) - 10)
print(100 / 10 / 2)
The computer follows the same math rules you learned in school.