Trusted answers to developer questions

What is a modulo operator (%) in Python?

Get the Learn to Code Starter Pack

Break into tech with the logic & computer science skills you’d learn in a bootcamp or university — at a fraction of the cost. Educative's hand-on curriculum is perfect for new learners hoping to launch a career.

The Python modulo operator, %, is used to retrieve the remainder after a division.

The basic syntax of the python modulo used in an equation is as follows:

# Syntax to get a remainder from a division in Python
argument1 % argument2 = remainder of (argument1/argument2)

Examples

In this example, when we divide the first argument, 6, by the second argument, 2 - the result of the division is 3 with 0 as a remainder.

So in Python, 6 % 2 = 0

svg viewer

In this example, when we divide the first argument, 9, by the second argument, 7 - the result of the division is $ {1}\frac{2}{7}$ with 2 as a remainder.

So in Python, 9 % 7 = 2

svg viewer

Exceptions with the Python Modulo Operator

The only exception you get with a python modulo operator ‘%’ is when the second argument is 0. This means that the divider operand of the modulo operator cannot be zero.

For example:

svg viewer
argument1 = 8
argument2 = 0
exceptionRemainder = argument1 % argument2
print(exceptionRemainder)

RELATED TAGS

modulo
python
operator
Copyright ©2024 Educative, Inc. All rights reserved
Did you find this helpful?