Floor division, remainder and powers

Numbers & Math, lesson 2 of 5

🔢 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 ** 3 is 2 × 2 × 2 = 8

Think of sharing 17 sweets among 5 friends: each gets 17 // 5 = 3, and 17 % 5 = 2 are left over.

Example

Sharing sweets

Change sweets to 20. What is the remainder now?

Walkthrough

Sharing 17 sweets among 5 friends

F1F2F3F4F5round 1round 2round 3left over12345
Step 1 of 4

Round 1: every friend gets one sweet. 5 handed out, 12 still in the bag.

handed out this round
left over

Each column is a friend. Sweets are handed out one round at a time, one sweet per friend per round.

Quiz

What does this print?

% has classic uses:

  • n % 2 is 0 for even numbers and 1 for odd ones
  • n % 10 gives the last digit of a positive number
  • // and % together convert units, like seconds into minutes and seconds
Example

Handy remainders

Try seconds = 3725. Can you also work out the hours?

Walkthrough

Rounding down on the number line

-4-3-2-1012343.5-3.5
Step 1 of 2
7 / 2 = 3.5
7 // 2 = 3

7 / 2 is 3.5, between 3 and 4. Rounding down means moving left, so 7 // 2 is 3.

between these whole numbers

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.

Example

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.

Quiz

What does this print?

Exercise

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).

Quiz

Which expression is 0 exactly when n is even?