Home
Map
divmod Examples (Modulo)Use the divmod built-in to combine division and modulo division in a single statement.
Python
This page was last reviewed on Jun 26, 2023.
Divmod. 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.
An example. Divmod combines two division operators. It performs an integral division and a modulo division. It returns a two-item pair (a tuple).
Tuple
Return The first element is the result of the integral division. And the second is the modulo result.
Info You can compute these numbers with the "/" and "%" operators. This sometimes does not apply for floating-point numbers.
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
Make change with divmod. We can count coins with divmod. This method, make_change, changes "cents" into quarters, nickels, and cents. We repeatedly call divmod.
Tip This approach cannot make change in all combinations. A recursive method is able to generate all possibilities.
Recursion
Result The program discovers that 81 cents can be made with five coins together. This logic applies to any currency.
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)
Modulo. 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.
Tip Modulo is a good choice when an actual division is not needed. Otherwise, use divmod.
# Input values. a = 12 b = 7 # Use modulo operator. c = a % b print(c)
5
Modulo in loops. 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.
Here We display whether each index in the 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
Even, odd. 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.
Warning We cannot define 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)
Prime numbers. 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.
Prime
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.
Dot Net Perls is a collection of tested code examples. Pages are continually updated to stay current, with code correctness a top priority.
Sam Allen is passionate about computer languages. In the past, his work has been recommended by Apple and Microsoft and he has studied computers at a selective university in the United States.
This page was last updated on Jun 26, 2023 (edit).
Home
Changes
© 2007-2024 Sam Allen.