Data Types and Operations
Python numbers come in two data types: integers for whole numbers like 7, and floats for decimals like 3.75. Arithmetic operators do maths with them.
Integers and floats
A number with a decimal point is a float. Mixing an integer and a float gives a float.
print(7 + 2)print(1.5 + 2)This prints 9, then 3.5.
Arithmetic operators
+add,-subtract,*multiply/divide//floor division — divide, then round down to a whole number (7 // 2is3)%modulo — the remainder left over (7 % 2is1)
print(10 + 3)print(10 - 3)print(10 * 3)print(10 // 3)print(10 % 3)This prints 13, 7, 30, 3 and 1.
Dividing integers and floats
/ always gives a float, even when the division is exact.
print(6 / 3)print(10 / 4)This prints 2.0, then 2.5.
Order of operations
Python follows normal maths order: * and / happen before + and -.
Use brackets when you want a different order.
print(2 + 3 * 4)print((2 + 3) * 4)This prints 14, then 20.
See also: Variables.
Your turn
Add two lines: print a floor-divided by b, then print the remainder of
a divided by b.
3 2
a = 17b = 5# add two prints: floor division first, then the remainderAdvanced reading
- Rounding numbers —
round(), rounding ties and why0.1 + 0.2is not0.3. - Floor division, modulo and powers —
//and%below zero,divmod(),**powers and dividing by zero.