Floor division, remainder and power
🌍 In real life. You have 7 slices of pizza and 3 friends. You give one slice to each friend, round after round, until there aren't enough left to go round again. Each friend got 2 slices, and 1 slice is left over.
Two questions came out of that: how many full shares (2) and how many left over (1). Python has an operator for each one, plus one more for multiplying a number by itself.
The idea in one sentence: // counts how many full groups fit, % gives what's left over, and ** multiplies a number by itself again and again.
Its words:
//floor division: divide, then round down to a whole number%remainder (also called modulo): what's left over after dividing**power:2 ** 3means 2 × 2 × 2
Step by step, for 7 slices and 3 friends:
- Give everyone one slice: 4 left.
- Again: 1 left, not enough for another round.
- Rounds completed:
7 // 3is 2. Left over:7 % 3is 1.
print(7 // 3)
print(7 % 3)How Python does it. // and % are a team. For any whole numbers, a == (a // b) * b + a % b: the full shares, times the group size, plus the leftovers, gives back what you started with. For 7 and 3: 2 × 3 + 1 = 7.
This makes them handy for many everyday jobs:
- splitting units: minutes into hours and minutes
- even or odd:
n % 2is 0 for even numbers and 1 for odd ones - the last digit:
n % 10, andn // 10drops it
** grows very fast: 2 ** 10 is 1024, and 10 ** 6 is a million.
minutes = 135
print(minutes // 60, "hours")
print(minutes % 60, "minutes")print(10 % 2)
print(7 % 2)
print(10 % 2 == 0)year = 2024
print(year % 10)
print(year // 10)print(2 ** 3)
print(3 ** 2)
print(10 ** 6)Mistakes and edge cases.
- % isn't percent.
50 % 10is0, the remainder, not 5. For 10 percent of 50, write50 * 10 / 100. - ^ isn't power.
2 ^ 3gives1without any error (it's a different operator). Use2 ** 3. - Floats stay floats.
7.5 // 2is3.0, a whole number but still a float. - Negative numbers round down, not toward zero.
-7 // 2is-4, and-7 % 2is1. - Zero groups.
5 // 0and5 % 0raiseZeroDivisionError, just like/.
Quiz
What does this print?
print(17 // 5)What does this print?
print(17 % 5)What does this print?
print(2 ** 4)Which one checks whether
nis even?- n % 2 == 0
- n // 2 == 0
- n ** 2 == 0
What does this print?
print(20 % 4)This should print the area of a 4 by 4 square, 16, but it prints 6. Which line has the mistake?
side = 4 area = side ^ 2 print(area)
Coding tasks
You have 29 eggs, packed 12 to a box. Make
boxesthe number of full boxes andextrathe number of eggs left over.Print 5 to the power of 3.
secondsholds 200. Print the whole minutes and the leftover seconds, like this:3 20