Hone

Lessons · Python · // and %

Whole parts and what is left over

// gives how many whole times one number fits in another; % gives the remainder.

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

Minutes to hours, cents to dollars, items to boxes, every-Nth-item, odd or even: all of them are one // and one %.

How to think about it

How many whole groups, and what is left over? Ask two questions: how many whole groups, and how much did not fit. The first is //, the second is %. They always pair: a == (a // b) * b + a % b.

Worked example

total_minutes = 135
We want hours and minutes.
hours = total_minutes // 60
2. Two whole hours fit.
mins = total_minutes % 60
15. What was left.
print(f"{hours}:{mins:02d}")
2:15. The :02d pads to two digits.

Your turn

Is n even?

even = n  2 == 0

The trap

/ always gives a float in Python 3: 7 / 2 is 3.5, not 3. Use // when you want whole numbers.

Practise // and % on HoneA question on it now, a coding challenge where there is one, and it is remembered for review. Free, no email needed.