What is Modulo Operator in Python



The modulo operator is denoted by the "%" symbol in Python. It can also be called the remainder operator because it is used to return the remainder of the division of two numeric operands. Using this operator, we can solve problems ranging from simple to complex.

Syntax of Python Modulo Operator

The modulo operator in Python works the same as the remainder of dividing the two numeric operands. Following is the syntax of the modulo operator -

Result = a % b

Where a and b are the operands, % represents the modulo operator, and Result will store the remainder of dividing a by b.

Modulo Operator with Datatypes

In this section, we will understand the behaviour of the modulo operator with datatypes such as integers and floating-point numbers.

Modulo operator with integers

Using the modulo operator with integers is the most common use case of the modulo operator in Python

Example of modulo with Positive integers:

# Example of modulo with Positive integers
print(10 % 2)
print(34 % 5)
print(43 % 6)

Following is the output of the above program -

0
4
1

Example of modulo with Negative integers:

# Example of modulo with Negative integers
print(34 % -5)
print(-43 % 6)

Following is the output of the above program -

-1
5

In the above example, the result of 34%-5 is -1, and -43%6 is 5 because Python uses floor division for solving negative operands.

When we divide 34 by -5, we get -6.8. The floor of -6.8 is -7, which is the closest whole number less than or equal to -6.8. We then multiply -7 by -5, giving 35. Finally, we subtract this from 34: 34 minus 35 equals -1, which is the result of 34%-5 in Python. The same process applies to the second example.

Modulo operator with floating point numbers

The behaviour of the Python modulo operator with floating-point numbers is the same as with the integers. The only difference is that its result will be a float. Here is how it works:

Example of Modulo with Floating-point Numbers:

# Example of modulo with Floating point Numbers
print(3.4 % 2.2)
print(10.2 % 3.5)

Following is the output of the above program -

1.1999999999999997
3.1999999999999993

Example Of Python Modulo Operator

The following example demonstrates how to use the modulo operator in Python to get the seconds in the format of minutes and seconds.

total_seconds = 150

minutes = total_seconds // 60  # To determine how many full 60-second minutes fit into 150 seconds

seconds = total_seconds % 60  # It will gives us the remainder after removing the full minutes.

print(f"{minutes} minutes and {seconds} seconds")

Following is the output of the above program -

2 minutes and 30 seconds
Updated on: 2025-04-18T15:21:04+05:30

511 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements