🔢 Numbers & Math, lesson 2 of 5
Floor division, remainder and powers
Use //, % and ** to split things up and raise numbers to powers.
9 min
1 exercise
3 quizzes
0/4 solved
Getting Python ready… examples can run in a moment.
Three more operators are surprisingly useful:
//floor division: divides and rounds the result down to a whole number%modulo: the remainder left over after division**power:2 ** 3is 2 × 2 × 2 = 8
Think of sharing 17 sweets among 5 friends: each gets
17 // 5 = 3, and 17 % 5 = 2 are left over.
Sharing sweets
Change sweets to 20. What is the remainder now?
Sharing 17 sweets among 5 friends
Round 1: every friend gets one sweet. 5 handed out, 12 still in the bag.
Each column is a friend. Sweets are handed out one round at a time, one sweet per friend per round.
What does this print?
% has classic uses:
n % 2is0for even numbers and1for odd onesn % 10gives the last digit of a positive number//and%together convert units, like seconds into minutes and seconds
Handy remainders
Try seconds = 3725. Can you also work out the hours?
Rounding down on the number line
7 / 2 is 3.5, between 3 and 4. Rounding down means moving left, so 7 // 2 is 3.
The vertical line marks the exact answer of /. Each bar spans the two whole numbers around it, and // always picks the bar's left end.
Both results at once
divmod(a, b) gives a // b and a % b together, as two values at once. q, r = divmod(...) stores them in two variables. Change friends to 4 and predict both numbers.
What does this print?
Movie length
A movie lasts 135 minutes. Use // and % to
split it into whole hours and leftover minutes
(it should print 2 h 15 min).
Which expression is 0 exactly when n is even?
n // 2
n % 2
n ** 2
n / 2