← Intro to programming with Python

Whole-number division, remainders and powers

Use //, % and ** to split things into groups.

Start this lesson

Sometimes you only want whole things. If 135 minutes pass, how many FULL hours is that, and how many minutes are left over? Python has two operators for this. // (floor division) gives how many whole times one number fits into another, and % (remainder, also called modulo) gives what is left over. A third operator, **, means "to the power of", so 2 ** 3 is 2 * 2 * 2 = 8.

minutes = 135
print(minutes // 60)   # 2 full hours
print(minutes % 60)    # 15 minutes left over
print(2 ** 5)          # 32

60 fits into 135 two whole times (that is 120), and 135 - 120 = 15 is the remainder.

A handy trick: a number is even when number % 2 is 0, and odd when it is 1.

Common mistake: using ^ for powers. In Python ^ means something completely different, so 2 ^ 3 gives 1. Use 2 ** 3.

Remember: // and % go together. // answers "how many groups?" and % answers "how many left over?".