Python Divmod Examples, Modulo Operator

Use the divmod built-in to combine division and modulo division. The modulo operator is shown.

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.Numbers

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.Built-ins

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
Elements: The first element is the result of the integral division. And the second is the modulo result.
Usually: You can compute these numbers with the "/" and "%" operators. This sometimes does not apply for floating-point numbers.
Python program that uses divmod a = 12 b = 7 # Call divmod. x = divmod(a, b) # The first part. print(x[0]) # The second part (remainder). print(x[1]) Output 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.
Result: The program discovers that 81 cents can be made with five coins together. This logic applies to any currency.
Python program that makes change with 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) Output ('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.
Python program that uses modulo # Input values. a = 12 b = 7 # Use modulo operator. c = a % b print(c) Output 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.
Python program that uses modulo division in loop # 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) Output 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.
Python program that tests for even, 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)) Output ('#', '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 Number

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.

© 2007-2020 Sam Allen. Every person is special and unique. Send bug reports to info@dotnetperls.com.