Learn Python · lesson 9 of 60 · about 7 minutes
Integer Maths and Precedence
Turn the assistant's 5.0 weeks into whole weeks and what's left over with // and %, and see why its brackets matter.
What you'll learn
- Use floor division // and remainder %
- Predict operator precedence
- Update variables with += -= *=
5.0 weeks?
Your assistant says the bike is 5.0 weeks away, because / always gives a float. Weeks come in whole numbers, and when a sum doesn't divide exactly, you'd also want to know what's left over. Python has an operator for each:
//divides and keeps only the whole part:80 // 15is5%gives the remainder:80 % 15is5, the part that didn't make a whole week
Whole weeks and what's left
left = 80
weekly = 15
print(left / weekly)
print(left // weekly)
print(left % weekly)Output
5.333333333333333
5
5Even numbers and clocks
% turns up everywhere. n % 2 is 0 for even numbers and 1 for odd ones, and // and % together split one number into two: 135 minutes is 135 // 60 hours and 135 % 60 minutes.
135 minutes, split
minutes = 135
print(f"{minutes // 60} h {minutes % 60} min")Output
2 h 15 minWhich sum goes first
Python follows the order from maths: brackets first, then ** (power), then *, /, // and %, then + and -. That's why your assistant has brackets in (price - saved) / weekly. Without them, Python divides saved first.
Brackets change the answer
price = 120
saved = 45
weekly = 15
print(price - saved / weekly)
print((price - saved) / weekly)Output
117.0
5.0Shortcut updates
To change a variable using its own value, saved = saved + 15 works, and saved += 15 is the short way to write it. -=, *= and //= work the same way.
Updating saved, the short way
saved = 45
saved += 15
saved -= 10
print(saved)Output
50Tip
Dividing by zero crashes with a ZeroDivisionError, whether you use /, // or %.
Now try it yourself
This lesson is free in Codiqo, with 11 questions on what you just read. You can only learn to code by writing code, so it ends with a short program you write yourself, which we run and check straight away.