Numbers and operators: maths, comparisons and logic
Calculate with Python's arithmetic operators, use division, remainder and power, compare values and combine conditions with and, or and not.
In this lesson you will
- Use arithmetic operators
- Understand /, // and %
- Compare values to get True or False
- Combine conditions with and, or, not
About 17 minutes
Python as the world’s cleverest calculator
You are at a shop. Three notebooks at 120 rupees each, one pen at 45, and you want to know the total and whether 500 is enough. That small story uses addition, multiplication and a comparison. In Python, symbols called operators do this work, and they behave almost exactly as they did in school.
Arithmetic operators
| Operator | Meaning | Example | Result |
|---|---|---|---|
+ |
Add | 7 + 3 |
10 |
- |
Subtract | 7 - 3 |
4 |
* |
Multiply | 7 * 3 |
21 |
/ |
Divide (always a float) | 7 / 2 |
3.5 |
// |
Floor division (whole part) | 7 // 2 |
3 |
% |
Remainder (modulo) | 7 % 2 |
1 |
** |
Power | 2 ** 3 |
8 |
notebooks = 3 * 120
pen = 45
total = notebooks + pen
print("Total:", total)
print("Change from 500:", 500 - total)
Total: 405
Change from 500: 95
Division in three flavours
print(17 / 5) # true division: 3.4
print(17 // 5) # floor division: how many whole times? 3
print(17 % 5) # remainder: what is left over? 2
print(divmod(17, 5)) # both at once
3.4
3
2
(3, 2)
The remainder operator is wonderfully useful. A number is even when n % 2 == 0. Clock arithmetic is a remainder: 15:00 is 3 o’clock because 15 % 12 is 3. And // and % together convert 135 minutes into hours and minutes:
minutes = 135
hours = minutes // 60
left = minutes % 60
print(hours, "hours and", left, "minutes")
2 hours and 15 minutes
Order of operations
print(2 + 3 * 4) # multiplication first: 14
print((2 + 3) * 4) # brackets first: 20
print(2 ** 3 ** 2) # powers go right to left: 512
print(10 - 4 - 3) # left to right: 3
14
20
512
3
Even when you know the order, add brackets to make your intention obvious. (a * b) + c is easier to read than a * b + c.
Shortcuts for updating a variable
lives = 3
lives -= 1 # lives = lives - 1
print(lives)
points = 10
points += 5 # points = points + 5
points *= 2 # points = points * 2
print(points)
level = 1
level += 1
print(level)
2
30
2
Useful built-in maths
print(abs(-7)) # distance from zero: 7
print(round(3.14159, 2)) # round to 2 decimals: 3.14
print(round(2.5), round(3.5)) # banker's rounding: 2 4
print(max(4, 9, 2), min(4, 9, 2))
print(pow(2, 10))
print(sum([1, 2, 3, 4]))
7
3.14
2 4
9 2
1024
10
For more advanced maths, import the math module, a toolbox that ships with Python.
import math
print(math.sqrt(144))
print(math.pi)
print(math.ceil(4.1), math.floor(4.9))
print(round(math.sqrt(2), 4))
12.0
3.141592653589793
5 4
1.4142
Comparison operators: asking questions
Comparisons ask a question about two values and give back True or False. These answers power every decision your programs will make.
| Operator | Asks | Example | Result |
|---|---|---|---|
== |
Equal? | 5 == 5 |
True |
!= |
Not equal? | 5 != 3 |
True |
> |
Greater than? | 3 > 5 |
False |
< |
Less than? | 3 < 5 |
True |
>= |
Greater or equal? | 5 >= 5 |
True |
<= |
Less or equal? | 4 <= 3 |
False |
age = 20
print(age >= 18)
print(age == 21)
print(1 < age < 30) # chained comparison, a Python favourite
print("apple" < "banana") # text compares alphabetically
True
False
True
True
Writing a single = when you mean to compare. = stores a value, == asks whether two values are equal. Python will give a syntax error if you try if x = 5:, which protects you from a bug that haunts other languages.
Logical operators: and, or, not
age = 20
has_ticket = True
print(age >= 18 and has_ticket) # both must be true
print(age < 13 or age > 65) # at least one true
print(not has_ticket) # flips the answer
can_enter = age >= 18 and has_ticket
print("Can enter:", can_enter)
True
False
False
Can enter: True
Read them aloud: “age is at least 18 and has a ticket”. Python code reads almost like English, which is the goal. and is strict, or is flexible, not is a mirror.
A float surprise
print(0.1 + 0.2)
print(round(0.1 + 0.2, 2) == 0.3)
0.30000000000000004
True
Computers store decimals in binary, which cannot represent some fractions exactly. The result is a tiny error. For everyday work, round the result. For money, many programs store whole cents (integers) or use the decimal module.
A taxi charges 50 rupees to start and 18 rupees per kilometre. Store the distance as 7.5, calculate the fare and print it. Then print whether the fare is more than 200.
Show one possible answer
distance = 7.5
fare = 50 + 18 * distance
print("Fare:", fare)
print(fare > 200)
Fare: 185.0
False
Convert 3725 seconds into hours, minutes and seconds using // and %.
Hint: Work from the biggest unit down, using the remainder each time.
Show one possible answer
seconds = 3725
hours = seconds // 3600
minutes = (seconds % 3600) // 60
rest = seconds % 60
print(hours, "h", minutes, "min", rest, "s")
1 h 2 min 5 s
Check what you learned
Five quick questions. Pick an answer and you will see straight away whether it is right and why.
What is 17 // 5?
- 3.4
- 3
- 2
- 5
Floor division gives the whole part of the answer.
What is 17 % 5?
- 3
- 3.4
- 12
- 2
The remainder of 17 divided by 5 is 2.
What does 2 + 3 * 4 equal?
- 20
- 14
- 24
- 9
Multiplication happens before addition.
What does 5 == 5.0 return?
- False
- Error
- None
- True
The values are equal even though the types differ.
Which operator keeps a decision true only if both parts are true?
andornot!=
and needs both sides to be True.
Summary
- / always gives a float, // gives the whole part, % gives the remainder.
- Brackets control the order.
- Comparisons return True or False.
- and, or and not combine conditions.
Questions
Why does 0.1 + 0.2 not equal 0.3?
Decimals are stored in binary, which cannot represent every fraction exactly. Round when you compare.
What is the difference between == and is?
== compares values. is checks whether two names point to the very same object. Use == for comparing values.
How do I do square roots?
Use math.sqrt(x) after import math, or x ** 0.5.
