Python 3D Academyবাংলা

Floor division, remainder and power

🌍 In real life. You have 7 slices of pizza and 3 friends. You give one slice to each friend, round after round, until there aren't enough left to go round again. Each friend got 2 slices, and 1 slice is left over.

Two questions came out of that: how many full shares (2) and how many left over (1). Python has an operator for each one, plus one more for multiplying a number by itself.

The idea in one sentence: // counts how many full groups fit, % gives what's left over, and ** multiplies a number by itself again and again.

Its words:

  • // floor division: divide, then round down to a whole number
  • % remainder (also called modulo): what's left over after dividing
  • ** power: 2 ** 3 means 2 × 2 × 2

Step by step, for 7 slices and 3 friends:

  1. Give everyone one slice: 4 left.
  2. Again: 1 left, not enough for another round.
  3. Rounds completed: 7 // 3 is 2. Left over: 7 % 3 is 1.
print(7 // 3)
print(7 % 3)

How Python does it. // and % are a team. For any whole numbers, a == (a // b) * b + a % b: the full shares, times the group size, plus the leftovers, gives back what you started with. For 7 and 3: 2 × 3 + 1 = 7.

This makes them handy for many everyday jobs:

  • splitting units: minutes into hours and minutes
  • even or odd: n % 2 is 0 for even numbers and 1 for odd ones
  • the last digit: n % 10, and n // 10 drops it

** grows very fast: 2 ** 10 is 1024, and 10 ** 6 is a million.

minutes = 135
print(minutes // 60, "hours")
print(minutes % 60, "minutes")
print(10 % 2)
print(7 % 2)
print(10 % 2 == 0)
year = 2024
print(year % 10)
print(year // 10)
% 10 gives the last digit, 4, and // 10 drops it, leaving 202.
print(2 ** 3)
print(3 ** 2)
print(10 ** 6)

Mistakes and edge cases.

  • % isn't percent. 50 % 10 is 0, the remainder, not 5. For 10 percent of 50, write 50 * 10 / 100.
  • ^ isn't power. 2 ^ 3 gives 1 without any error (it's a different operator). Use 2 ** 3.
  • Floats stay floats. 7.5 // 2 is 3.0, a whole number but still a float.
  • Negative numbers round down, not toward zero. -7 // 2 is -4, and -7 % 2 is 1.
  • Zero groups. 5 // 0 and 5 % 0 raise ZeroDivisionError, just like /.

Quiz

  1. What does this print?

    print(17 // 5)
  2. What does this print?

    print(17 % 5)
  3. What does this print?

    print(2 ** 4)
  4. Which one checks whether n is even?

    • n % 2 == 0
    • n // 2 == 0
    • n ** 2 == 0
  5. What does this print?

    print(20 % 4)
  6. This should print the area of a 4 by 4 square, 16, but it prints 6. Which line has the mistake?

    side = 4
    area = side ^ 2
    print(area)

Coding tasks

  1. You have 29 eggs, packed 12 to a box. Make boxes the number of full boxes and extra the number of eggs left over.

  2. Print 5 to the power of 3.

  3. seconds holds 200. Print the whole minutes and the leftover seconds, like this:

    3 20