← CS Unplugged

CS Unplugged activity

Modulo in Real Programs

About 20 minutesSoloPencil

Python’s % operator computes a remainder: a % b is what’s left over after dividing a by b as many whole times as it goes. That one small idea shows up all over real programs, usually in disguise. Here are five places you’ve probably already run into it.

Even or odd

Any whole number is even if n % 2 is 0, and odd if it’s 1. There’s nothing else it can be.

n = 17
print(n % 2)

Predict this: what prints?

Wrapping around a list

A carousel of colors, a rotation of players, a board game space you loop back onto: anything that cycles through a fixed-size list uses % len(...) to wrap the index back to the start instead of running off the end.

colors = ["red", "green", "blue"]
i = 2
i = (i + 1) % len(colors)
print(colors[i])

Predict this: what prints?

Turning a robot

The AP robot faces one of 4 directions: 0 up, 1 right, 2 down, 3 left. Turning right adds 1 each time, but 4 turns should land you facing the same way you started. % 4 makes that happen automatically instead of you writing a special case for “wrapped past 3.”

facing = 3  # left
turns = 6
facing = (facing + turns) % 4
print(facing)

Predict this: what prints (0, 1, 2, or 3)?

Minutes into hours and minutes

// (floor division) and % are a matched pair: // gives the whole groups, % gives what’s left over. A total number of minutes splits into hours and minutes the same way a total number of cents splits into dollars and cents.

total = 135
hours = total // 60
minutes = total % 60
print(hours, minutes)

Predict this: what prints?

The Caesar cipher’s wraparound

The Caesar cipher shifts every letter the same number of places through the alphabet. Numbering A to Z as 0 to 25, shifting past Z has to wrap back to A, and % 26 is exactly what does the wrapping.

letter = 24  # Y
shift = 5
new_letter = (letter + shift) % 26
print(new_letter)

Predict this: what prints (a number from 0 to 25)?

Now you trace it

Two more, mixing several of these ideas. Trace each one by hand before you write down what it prints.

  1. colors = ["red", "green", "blue", "yellow"]
    i = 3
    i = (i + 1) % len(colors)
    print(colors[i])
    

  2. facing = 1  # right
    turns = 9
    facing = (facing + turns) % 4
    print(facing)
    

Even or odd. 17 % 2 is 1.

Wrapping around a list. i becomes 0, so colors[0] prints red.

Turning a robot. (3 + 6) % 4 is 1, which is facing right.

Minutes. 135 // 60 is 2, 135 % 60 is 15. Prints 2 15.

Caesar cipher. (24 + 5) % 26 is 3.

Now you trace it. (1) prints red. (2) prints 2 (down).

CC BY-NC-SA 4.0.