Python Modulo (%) Patterns: Wrap Around, Digits and Every Nth
Python's modulo % does more than test divisibility: it wraps counters around a cycle, pulls digits out of a number and picks every nth item.
Each pattern uses the same fact: a remainder always stays below the divisor.
Read Modulo and Divisibility first. You also need for loops, while loops, lists, range() and floor division // from Data Types and Operations.
Wrap around a cycle
i % n always lands between 0 and n - 1. Use it as a list index that wraps back to the start.
players = ["Ada", "Sam", "Lee"]
for turn in range(5):
print(turn, players[turn % 3])
This prints 0 Ada, 1 Sam, 2 Lee, 3 Ada, 4 Sam. Turns 3 and 4 wrap back to Ada and Sam. Without % 3, players[3] raises IndexError.
Use len(players) instead of 3 so the code still works when the list changes size. The divisor must be the cycle length: % 2 here would never reach Lee.
Clock arithmetic
Times wrap the same way. Add hours, then take % 24 to stay on a 24-hour clock.
start = 22
print((start + 5) % 24)
print((start + 26) % 24)
This prints 3, then 0. Adding 26 hours is a full day plus 2 more.
Pull digits out of a number
% 10 gives the last digit: the remainder after dividing by 10. // 10 divides by 10 and throws the remainder away, so it drops that digit. Repeat until the number is 0.
number = 4732
while number > 0:
print(number % 10)
number = number // 10
This prints 2, 3, 7, 4: the digits from right to left. Don't mix the two up: % keeps the remainder, // keeps the quotient. This works only for non-negative whole numbers; for a negative number, % 10 follows the divisor's sign (see Modulo with negative numbers).
Note: str(number) is often simpler when you only need to read the digits. Use % and // when you are doing arithmetic with them.
Every nth item
i % n == 0 is True once every n steps. Use it to act on a regular beat.
for i in range(1, 11):
if i % 4 == 0:
print(i, "bonus round")
This prints 4 bonus round, then 8 bonus round. Starting range() at 1 matters: 0 % 4 == 0 is also True.
See also: The range() function.
Your turn
Deal the six cards to the three players in turn, wrapping with %. Print each card and who gets it.
players = ["Ada", "Sam", "Lee"]
cards = [5, 9, 2, 7, 4, 8]
# loop over the positions of cards; use % to pick the player
Expected output
5 Ada
9 Sam
2 Lee
7 Ada
4 Sam
8 Lee