Lessons · Python · % the remainder
The remainder
a % b is what is left over after dividing a by b: 7 % 2 is 1.
Hone is a place to practise programming. This is one of its lessons, written out in full and free to read without an account.
What it is for
Odd or even, every third row shaded, wrapping a clock past 12, splitting seconds into minutes: all of them are remainders.
How to think about it
Ask what is left after taking out as many whole groups as fit. n % 2 is 0 for even numbers and 1 for odd; n % k is 0 exactly when k divides n.
Worked example
print(7 % 2)1: three twos fit, one is left.
print(10 % 5)0: five divides ten.
print(65 % 60)5: sixty-five seconds is one minute and five.
print(14 % 12)2: two o'clock, after wrapping past twelve.
Your turn
Is n even?
even = n 2 == 0
Solve one with the tests running
The trap
With a negative left side Python's remainder takes the sign of the divisor: -7 % 2 is 1, not -1. Other languages differ, which matters when porting.
Practise % the remainder on HoneA question on it now, a coding challenge where there is one, and it is remembered for review. Free, no email needed.