Learning objectives:
- Understand arithmetic, relational and Boolean operators (2.4.1–2.4.3)
- Use, interpret, create and debug code with operators (2.4.4–2.4.7)
Arithmetic operators
| Operator | Python | Example | Result |
|---|---|---|---|
| Add | + | 7 + 2 | 9 |
| Subtract | - | 7 - 2 | 5 |
| Multiply | * | 7 * 2 | 14 |
| Divide | / | 7 / 2 | 3.5 |
| Exponentiation | ** | 7 ** 2 | 49 |
| Integer division | // | 7 // 2 | 3 |
| Modulus (remainder) | % | 7 % 2 | 1 |
/ always gives a float. // gives the whole-number part. % is useful for checking if a number is even (n % 2 == 0).
Relational operators
These compare two values and give True or False.
| Meaning | Python |
|---|---|
| Equivalence (equal to) | == |
| Not equal | != |
| Less than | < |
| Greater than | > |
| Less than or equal to | <= |
| Greater than or equal to | >= |
Boolean operators
| Operator | Result is True when… |
|---|---|
not | the condition is False |
and | both conditions are True |
or | at least one condition is True |
age = 17
has_ticket = True
if age >= 16 and has_ticket:
print("Entry allowed")
Common operator bugs
- Using
=(assignment) instead of==(comparison). - Using
/when a whole number is needed, or//when the decimal matters. andandorthe wrong way round:age < 11 and age > 19can never be True; it should beor.- Boundaries:
> 18excludes 18;>= 18includes it.