Skip to content

Python remainder

  • by

In Python, you can calculate the remainder of a division operation using the modulo operator %. The modulo operator returns the remainder when one number is divided by another.

Here’s the syntax:

remainder = dividend % divisor
  • dividend is the number you want to divide.
  • divisor is the number you want to divide by.
  • % is the modulo operator that calculates the remainder of the division operation.
  • remainder is the variable where the resulting remainder will be stored.

You can replace dividend and divisor with any numerical values or variables in your code.

Here’s an example that demonstrates the syntax:

dividend = 17
divisor = 5

remainder = dividend % divisor
print(remainder) #2

Python remainder example

Here are a few examples of using the remainder operator (%) in Python:

Example 1: Checking if a number is even or odd

number = 15

if number % 2 == 0:
    print("The number is even.")
else:
    print("The number is odd.")

Example 2: Wrapping values within a range

value = 27
range_size = 10

wrapped_value = value % range_size
print(wrapped_value)

Example 3: Calculating days and weeks

total_days = 73

weeks = total_days // 7
days = total_days % 7

print("Weeks:", weeks)
print("Days:", days)

Output:

Python remainder

These are just a few examples showcasing the usage of the remainder operator in Python. The modulo operation is versatile and can be applied in various scenarios, including arithmetic calculations, pattern recognition, and more.

Note: IDE: PyCharm 2021.3.3 (Community Edition)

Windows 10

Python 3.10.1

All Python Examples are in Python 3, so Maybe its different from python 2 or upgraded versions.

Leave a Reply

Your email address will not be published. Required fields are marked *