Return the Remainder from Two Numbers
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`.
Deep Dive
1. The Challenge: Finding the Remainder
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.
2. Why It Matters
The modulo operator (%) is essential for checking if numbers are even or odd, cycling array indices, and wrapping time values.
3. The Python Solution
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
4. How Modulo Calculation Works
For positive integers, 10 % 3 divides 10 by 3 (which equals 3 whole parts, total 9) leaving 1 left over as the remainder.
5. Common Mistakes
- Division by Zero: Executing
x % 0raises aZeroDivisionError: integer division or modulo by zero. Always verifyy != 0before running modulo!
6. Next Steps
Use % for remainder calculations. Next, let's convert hours and minutes into seconds!
Next Up in Python Beginner Practice & Core Problem Solving
Return the Sum of Two Numbers
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.
Convert Minutes into Seconds
`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.
Calculate the Area of a Triangle
`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.