askvity

How to get the remainder of division in Python?

Published in Python Arithmetic 2 mins read

You can get the remainder of a division operation in Python using the modulo operator %.

The Modulo Operator (%)

The modulo operator (%) returns the remainder after division. It's a fundamental arithmetic operator in Python.

Syntax:

result = dividend % divisor

Where:

  • dividend is the number being divided.
  • divisor is the number dividing the dividend.
  • result is the remainder of the division.

Examples:

# Example 1: Basic remainder calculation
remainder = 10 % 3
print(remainder)  # Output: 1

# Example 2:  Divisible number (remainder is 0)
remainder = 12 % 4
print(remainder)  # Output: 0

# Example 3: Using negative numbers
remainder = -10 % 3
print(remainder)  # Output: 2 (behavior might vary in other languages)

remainder = 10 % -3
print(remainder) # Output: -2

# Example 4: Using floats
remainder = 10.5 % 3
print(remainder) # Output: 1.5

Use Cases:

  • Checking for Even or Odd Numbers: A number is even if number % 2 equals 0.
  • Cyclic Operations: Used to wrap around a sequence (e.g., days of the week).
  • Hashing Algorithms: Important in distributing data evenly.

Important Considerations:

  • The modulo operator works with both integers and floating-point numbers.
  • The sign of the result depends on the sign of the dividend.
  • Dividing by zero will raise a ZeroDivisionError.

In summary, the % operator provides a simple and efficient way to determine the remainder of a division operation in Python, making it a versatile tool for a variety of programming tasks.

Related Articles