Quick Overview
% gives the remainder and // the floor of the division, and divmod() returns both in one call. With negatives the result follows the divisor's sign, so -7 % 3 is 2.
There is a single operator in Python capable of providing the remainder of a division operation. Create a function remainder(x, y) that takes two numbers and returns the remainder.
The modulo operator (%) is essential for checking if numbers are even or odd, cycling array indices, and wrapping time values.
Use the modulo operator %:
def remainder(x, y):
return x % y
# Testing our function
print(remainder(1, 3)) # Output: 1
print(remainder(3, 4)) # Output: 3
print(remainder(-9, 45)) # Output: 36
print(remainder(5, 5)) # Output: 0
For positive integers, 10 % 3 divides 10 by 3 (which equals 3 whole parts, total 9) leaving 1 left over as the remainder.
x % 0 raises a ZeroDivisionError: integer division or modulo by zero. Always verify y != 0 before running modulo!Use % for remainder calculations. Next, let's convert hours and minutes into seconds!
A function with no return hands back None, so a forgotten one surfaces as a TypeError at the call site rather than at the line that actually caused it.
minutes * 60 returns an int when given an int, while / always produces a float regardless of the operands. Multiplication preserves the type; division does not.
base * height / 2 always yields a float in Python 3 because / never returns an int, even for whole numbers. // floors instead, which is almost never what an area wants.