Floor Division, Remainder, and Powers

Floor Division, Remainder, and Powers

Three more arithmetic operators.

// is floor division: it divides and drops the fractional part, keeping the whole number.

print(17 // 5)

Output:

3

% is the modulo operator: it gives the remainder after division. In other words, it tells you how much is left over after splitting a quantity into whole units.

print(17 % 5)

Output:

2

17 divided by 5 is 3 with 2 left over — // gives the 3, % gives the 2. Together they split a quantity into whole units and a remainder. A common use of %: a number is divisible by n exactly when number % n is 0.

** raises a number to a power:

print(2 ** 10)

Output:

1024

Exercise

The starter code creates minutes holding 200.

  1. Create hours — the number of whole hours in minutes, using //.
  2. Create leftover — the minutes that remain, using %.
  3. Create cube holding 4 ** 3.
  4. Print hours, leftover, and cube.

Run your code to see the output, then press Submit.

Tests

import unittest


class TestMoreArithmetic(unittest.TestCase):
    def test_hours_is_3(self):
        self.assertEqual(hours, 3)

    def test_leftover_is_20_minutes(self):
        self.assertEqual(leftover, 20)

    def test_cube_is_64(self):
        self.assertEqual(cube, 64)
minutes = 200

hours = minutes // 60
leftover = minutes % 60
cube = 4 ** 3

print(hours)
print(leftover)
print(cube)
Solution hidden. Give it a real try first.

Sign in to join the discussion.

No comments yet. Be the first to ask a question.

main.py
Console
Press Run to execute your code, or Submit to test and complete this problem.