Numbers & operators
Handout
This page needs a recent browser (with SharedArrayBuffer support). Please update Chrome, Edge, Firefox or Safari to the latest version.
Two kinds of number
- An integer (
int) is a whole number, like7or-3. - A float is a number with a decimal point, like
2.5. - Division with
/always gives a float, even4 / 2→2.0.
Add, subtract, multiply, divide
+adds,-subtracts,*multiplies,/divides.- You can use them with variables or with plain numbers.
- Spaces around operators are optional but make code easier to read.
print(7 + 2)
print(7 - 2)
print(7 * 2)
print(7 / 2)
Whole-number division, remainder, powers
//divides and keeps only the whole part (floor division).%gives the remainder (called modulo).**raises to a power:2 ** 3is 2×2×2.
print(7 // 2)
print(7 % 2)
print(2 ** 5)
Order of operations
- Python does
**first, then*///%, then+-. - This is the same order you use in maths.
- Use parentheses
(...)to change the order.
print(2 + 3 * 4)
print((2 + 3) * 4)
Now you try
- Store each answer in the variable named in the task.
- Press Check answer to test your code.
Set length to 8 and width to 5. Then store their product in a variable called area.
Click Run to see the output here.
You share 17 sweets among 5 children. Store how many each child gets in each (use //), and how many are left over in left (use %).
Click Run to see the output here.
Store 3 ** 2 + 1 in result. Then use parentheses to store (3 + 1) ** 2 in grouped.
Click Run to see the output here.