The Modulo Operator in Python

What is the output of this code snippet?


for num in range(2, 8):
if num % 2 == 0:


This puzzle prints all odd values between two (included) and eight (excluded). To achieve this, we check whether the current value num can be divided by 2 without remainder. Python, like other languages, uses the percentage symbol % as modulo operator. This modulo operator returns the remainder when dividing a number n by another number x. For example, 12 % 2 = 0 as there is no remainder and 13 % 2 = 1 as the remainder is 1.

There is a second language feature in the puzzle which is the continue operator. This operator commands the interpreter to finish the current loop iteration. Then, the interpreter proceeds with the next iteration.

Hence, if the loop variable has an even value, the interpreter skips the print statement. If the loop variable has an odd value, the interpreter skips the continue statement.

Are you a master coder?
Test your skills now!


Related Video




Leave a Comment

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