Division and modulo division are related operations. With division, the result is stored in a single number. With modulo division, only the remainder is returned.
With divmod
, a built-in operator, we separate the two result values in a division. We get both the whole number of times the division occurs, and the remainder.
Divmod combines two division operators. It performs an integral division and a modulo division. It returns a two-item pair (a tuple).
a = 12 b = 7 # Call divmod. x = divmod(a, b) # The first part. print(x[0]) # The second part (remainder). print(x[1])1 5
divmod
We can count coins with divmod
. This method, make_change
, changes "cents" into quarters, nickels, and cents. We repeatedly call divmod
.
def make_change(cents):
# Use modulo 25 to find quarter count.
parts = divmod(cents, 25)
quarters = parts[0]
# Use modulo 5 on remainder to find nickel count.
cents_remaining = parts[1]
parts = divmod(cents_remaining, 5)
nickels = parts[0]
# Pennies are the remainder.
cents_remaining = parts[1]
# Display the results.
print("Argument:", cents)
print("Quarters:", quarters)
print("Nickels:", nickels)
print("Pennies:", cents_remaining)
# Test with 81 cents.
make_change(81)('Argument:', 81)
('Quarters:', 3)
('Nickels:', 1)
('Pennies:', 1)
Here we use the "%" symbol. Modulo computes the remainder of a division. The numbers are divided as normal, but the expression returns the amount left over.
divmod
.# Input values. a = 12 b = 7 # Use modulo operator. c = a % b print(c)5
Sometimes loops need to vary their behavior once every few iterations. A modulo in an if
-statement is ideal for this. We take action based on the index's value.
for
-loop is evenly divisible by 2, 3 and 4.# Loop over values from 0 through 9.
for i in range(0, 10):
# Buildup string showing evenly divisible numbers.
line = str(i) + ":"
if (i % 4) == 0:
line += " %4"
if (i % 3) == 0:
line += " %3"
if (i % 2) == 0:
line += " %2"
# Display results for this line.
print(line)0: %4 %3 %2
1:
2: %2
3: %3
4: %4 %2
5:
6: %3 %2
7:
8: %4 %2
9: %3
These methods test the parity of numbers. With even, all numbers are evenly divisible by 2. With odd, no numbers are evenly divisible by 2—a remainder of 1 or -1 is always left.
odd()
by testing for a remainder of 1. This will fail on negative numbers, which are validly odd numbers.def even(number): # Even numbers have no remainder when divided by 2. return (number % 2) == 0 def odd(number): # Odd numbers have 1 or -1 remainder when divided by 2. return (number % 2) != 0 # Test even and odd methods. print("#", "Even?", "Odd?") for value in range(-3, 3): print(value, even(value), odd(value))('#', 'Even?', 'Odd?') (-3, False, True) (-2, True, False) (-1, False, True) (0, True, False) (1, False, True) (2, True, False)
With primes, we cannot divide by any number except 1 and the number itself. In a for
-loop, we can test for primes by using modulo division.
Divmod, and its lower-level friend modulo, have many uses in programs. They are essential. We can make change, control loops, and test for specific number properties like parity.