Altcademy - a Forbes magazine logo Best Coding Bootcamp 2023

What is % in Python

Understanding the Percentage Sign (%) in Python

When you're starting out with Python, or any programming language for that matter, you'll come across various symbols that may seem confusing at first. One such symbol is the percentage sign %. In Python, % is known as the modulo operator. But what does it actually do?

The Modulo Operator: A Simple Explanation

Think of the modulo operation as the process of finding the remainder after division. For example, when you divide 10 by 3, you get 3 with a remainder of 1. In Python, this remainder is what % helps you find.

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

In the above code, 10 % 3 is asking, "What's the remainder when 10 is divided by 3?" The answer, 1, is stored in the variable remainder.

Modulo in Everyday Life

To give you an intuition about the modulo operation, let's take an everyday example. Imagine you have 10 apples and you want to distribute them evenly among 3 friends. Each friend will get 3 apples, and you'll have 1 apple left over. The modulo operation is like asking, "How many apples will I have left after sharing them equally?"

Common Uses of Modulo in Programming

Checking Even or Odd Numbers

One common use of the modulo operator is to check whether a number is even or odd. An even number is any number that can be divided by 2 without a remainder, while an odd number will have a remainder of 1 when divided by 2.

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

Cycling Through a Range

Another use for the modulo operator is to cycle through a range of numbers. This can be useful in scenarios like creating a loop that goes back to the start once it reaches the end, similar to how clock numbers go from 12 back to 1.

for i in range(10):
    print(i % 5)  # This will print a sequence: 0, 1, 2, 3, 4, 0, 1, 2, 3, 4

The Modulo and Integer Division

In Python, when you use the division operator /, you get a floating-point number (a number with a decimal point). However, if you want to perform integer division, which disregards the remainder and only gives you the whole number part of the division, you use //.

integer_division = 10 // 3
print(integer_division)  # Output: 3

It's important to note that integer division and modulo are closely related. In fact, they can be used together to get both the quotient and the remainder of a division.

quotient = 10 // 3
remainder = 10 % 3

print("Quotient:", quotient)  # Output: Quotient: 3
print("Remainder:", remainder)  # Output: Remainder: 1

Modulo with Negative Numbers

Things get a bit trickier when you start using modulo with negative numbers. The rule still applies—it finds the remainder—but the result might not be what you'd initially expect.

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

Why is the result 2 and not -1? When you use modulo with a negative number in Python, it still returns a positive remainder. It's as if you're asking, "If I were to add some multiples of 3 to -10, what's the smallest positive number I could get?"

Practical Code Examples

Using Modulo in a Function

Let's create a function that uses the modulo operator to check for leap years. A leap year is a year that is evenly divisible by 4, except for end-of-century years which must be divisible by 400. This means that the year 2000 was a leap year, but 1900 was not.

def is_leap_year(year):
    if (year % 4 == 0 and year % 100 != 0) or (year % 400 == 0):
        return True
        return False

print(is_leap_year(2000))  # Output: True
print(is_leap_year(1900))  # Output: False

Creating a Simple Timer

Imagine you're creating a simple timer that counts seconds and resets to 0 after reaching 59. The modulo operator is perfect for this task.

seconds = 0

while True:
    print("Timer:", seconds)
    # Wait for 1 second (not implemented here for simplicity)
    seconds = (seconds + 1) % 60

Conclusion: The Modulo Operator's Versatility

The % symbol in Python, while seemingly simple, is a versatile tool in your programming toolkit. It's essential for tasks that involve division with remainders, cycling through values, and creating conditions within your code. As you've seen through various examples, understanding how to use the modulo operator can help you solve a range of practical problems, from determining leap years to creating timers.

As you continue your journey in programming, remember that these small building blocks, like the modulo operator, are the keys to crafting complex and efficient code. They're like the hidden gears in a watch, small yet critical in making the whole system work. So next time you see % in Python, you'll know it's more than just a percent sign—it's a gateway to a world of possibilities in your coding adventures.