Operators I

Advanced Arithmetic Operators in Python

In this lesson you will learn about the floor division and the modulo operator in Python.


You already learnt about the basic arithmetic operators in Python:

# Addition 3 + 5 # Subtraction 3 - 5 # Multiplication 3 * 5 # Division 3 / 5 # Exponent 3 ** 5
Python

Another arithmetic operator in Python is the Floor Division operator //.

Just like a normal division, the Floor Division operator divides the first argument by the second. The difference is that the result is rounded down to the nearest whole number:

# normal division print(5 / 3) # floor division print(5 // 3)
Python
Output

What will be the output?

print(10 // 3)
Python

What will be the output?

print(11 // 4)
Python

Another special operator in Python is the Modulo operator %. It's used to get the remainder of a division.

The remainder of a division is what's left of a number after you check how many times another number fits into the first one.

Here, the result is 2 because 3 fits 3 times into 11 which is a total of 9. Therefore, the remainder is 11 - 9 = 2.

# modulo print(11 % 3)
Python
Output

You can also make use of the floor division operator to get the remainder. Here, both calculations have the same result. Try to understand why:

a = 13 b = 5 print(a - a // b * b) print(a % b)
Python
Output

An important characteristic of the modulo operator is that if number a is a multiple of number b, then a % b is always zero:

# remainder is zero because 3 * 5 = 15 print(15 % 3) # remainder is zero because 4 * 5 = 20 print(20 % 4)
Python
Output

The modulo operator can be very helpful in certain scenarios. One such scenario is to determine if a number is even or not.

This is because even numbers can be divided by two. In other words, an even number is always a multiple of 2. Therefore, the remainder of modulo two of an even number is always zero:

# if the remainder is zero, the number is even print(12 % 2) # even print(11 % 2) # not even print(4 % 2) # even print(55 % 2) # not even print(226 % 2) # even
Python
Output

What will be the output?

print(7%2)
Python

What will be the output?

print(20%11)
Python

What will be the output?

print(10%5)
Python