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

2 quizzes

0/3 solved

Getting Python ready… examples can run in a moment.

Three more operators are surprisingly useful:

  • // floor division: divides and drops the fractional part (rounds down)
  • % 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?

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 number
  • // and % together convert units, like seconds into minutes and seconds
Example

Handy remainders

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

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?