Find the division remainder of a number
Here's the quick way: use the %
operator to get the remainder.
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
.
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?
Math precision with math.remainder()
math.remainder()
provides a precise calculation of remainders, according to the IEEE 754 standard. For the nerdiest among us! 😉
Partner in crime: floor division operator
For those times when you just want the integer quotient without the remainder, use the floor division operator //
.
Custom modulo operations
For that rare time when you need a custom behavior, here’s how you can implement your own modulo operation:
Important cases and application examples
Dealing with negatives
Here's what happens when the dividend is negative with the modulo operator:
When precision becomes an issue
Now let's see what happens when we use a floating-point number:
Avoiding division by zero
And remember never to divide by zero - avoid such a mathematical apocalypse:
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:
-
Cycling through a list indefinitely:
-
Calculating days since epoch, e.g., number of days left in a week:
Was this article helpful?