Explain Codes LogoExplain Codes Logo

Find the division remainder of a number

python
math
functions
best-practices
Nikita BarsukovbyNikita Barsukov·Dec 8, 2024
TLDR

Here's the quick way: use the % operator to get the remainder.

remainder = 7 % 5 print(remainder) # Outputs: 2

Great! Now let's dive a bit deeper.

The modulo operator and divmod function

Basic remainders with % operator

To calculate the remainder of a division, you can use the modulo (%) operator. The format is numerator % denominator.

# This will return the remainder of 26 divided by 7... Spoiler: it's 5. remainder = 26 % 7 print(remainder) # Outputs: 5

Getting both quotient and remainder with divmod()

Use divmod(n, d) to get both the quotient and the remainder. It returns them as a tuple (quotient, remainder). Handy, right?

# Shortcut to maths: how many full 60s fit into 137, and what's left. You get (2, 17) quot, rem = divmod(137, 60) print(quot, rem) # Outputs: 2 17

Math precision with math.remainder()

math.remainder() provides a precise calculation of remainders, according to the IEEE 754 standard. For the nerdiest among us! 😉

# Hello, high precision! import math result = math.remainder(137, 60) print(result) # Can output a float!

Partner in crime: floor division operator

For those times when you just want the integer quotient without the remainder, use the floor division operator //.

# Show integer only. Robs the remainder. Meanie! integer_only = 137 // 60 print(integer_only) # Outputs: 2

Custom modulo operations

For that rare time when you need a custom behavior, here’s how you can implement your own modulo operation:

# Annoyed by Python's modulo? Make your own. Power to the people! def custom_modulo(numerator, denominator): if denominator <= 0: raise ValueError("Oh shoot! Can't divide by zero or negative, remember?") return numerator - ((numerator // denominator) * denominator) print(custom_modulo(26, 7)) # Outputs: 5

Important cases and application examples

Dealing with negatives

Here's what happens when the dividend is negative with the modulo operator:

# A little clarity: 26 / 7 = 14 remainder -3. # But we don't like negatives, so we add 7, getting us to 4. print(-26 % 7) # Outputs: 4

When precision becomes an issue

Now let's see what happens when we use a floating-point number:

# Check the 'lie-meter'! This should be just below 2.5. print(2.5 % 0.1) # something just a smidge over .09999999999999973

Avoiding division by zero

And remember never to divide by zero - avoid such a mathematical apocalypse:

# Try this, but never ever in a production code! result = 26 % 0

Modulo in the real world

Beyond pure math, here are some practical use cases where modulo rocks:

  • Checking if the number is even or odd:

    # Is this even, or prime number territory? number = 42 if number % 2 == 0: print("Even") else: print("Odd")
  • Cycling through a list indefinitely:

    # Fear of 'list index out of range'? # Taming Python lists... Let’s roll! colors = ["red", "green", "blue"] for i in range(10): color = colors[i % len(colors)] print(color)
  • Calculating days since epoch, e.g., number of days left in a week:

    # How to confuse the Python time service. # Let's find out which day it would be... if we only had weeks, and started from zero. days_since_epoch = 12345 dayThisWeek = days_since_epoch % 7