Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
What is modulo % operator in Python?
The modulo operator is denoted by the "%" symbol in Python. It returns the remainder of the division between two numeric operands, making it useful for solving problems ranging from simple arithmetic to complex mathematical operations.
Syntax
The modulo operator works by returning the remainder after dividing two numbers ?
result = a % b
Where a and b are the operands, % represents the modulo operator, and result stores the remainder of dividing a by b.
Modulo Operator with Integers
Using the modulo operator with integers is the most common use case. Let's see examples with both positive and negative integers.
Positive Integers
# Example of modulo with positive integers print(10 % 2) print(34 % 5) print(43 % 6)
0 4 1
Negative Integers
# Example of modulo with negative integers print(34 % -5) print(-43 % 6)
-1 5
With negative operands, Python uses floor division. For 34 % -5: dividing 34 by -5 gives -6.8, the floor is -7, then 34 - (-7 × -5) = 34 - 35 = -1.
Modulo Operator with Floating-Point Numbers
The modulo operator works similarly with floating-point numbers, returning a float result ?
# Example of modulo with floating-point numbers print(3.4 % 2.2) print(10.2 % 3.5)
1.1999999999999997 3.1999999999999993
The slight precision differences are due to how floating-point numbers are stored in binary format.
Practical Example
Here's how to convert total seconds into minutes and seconds format using the modulo operator ?
total_seconds = 150
minutes = total_seconds // 60 # Floor division for full minutes
seconds = total_seconds % 60 # Modulo for remaining seconds
print(f"{minutes} minutes and {seconds} seconds")
2 minutes and 30 seconds
Common Use Cases
| Use Case | Example | Purpose |
|---|---|---|
| Even/Odd Check | n % 2 == 0 |
Check if number is even |
| Cycling Values | index % length |
Wrap around in arrays |
| Time Conversion | seconds % 60 |
Extract remaining seconds |
Conclusion
The modulo operator (%) returns the remainder after division and works with both integers and floating-point numbers. It's particularly useful for cycling values, checking divisibility, and time conversions.
