Understanding Odd Numbers
An odd number is any integer that cannot be divided evenly by 2. When you divide an odd number by 2, the remainder is always 1. For example, numbers like 1, 3, 5, and 7 are odd because they leave a remainder of 1 when divided by 2. In contrast, even numbers like 2, 4, 6, and 8 are divisible by 2 with no remainder.
Implementation Approaches
Method 1: Using the continue Statement
The continue statement in Python allows you to skip the rest of the current loop iteration and move on to the next one. Here's how to use it for printing odd numbers:
for num in range(101):
if num % 2 == 0:
continue
print(num)
In this code, we iterate through all numbers from 0 to 100. The modulo operator % checks if a number is divisible by 2. When we encounter an even number, the continue statement immediately jumps to the next iteration, skippnig the print() call. Only odd numbers proceed to the print statement.
Method 2: Using the range() Step Parameter
Python's range() function accepts a third parameter that defines the step increment. We can leverage this to iterate only through odd numbers:
for num in range(1, 101, 2):
print(num)
By starting at 1 and incrementing by 2, we automatically generate only odd numbers. This approach is more efficient because it eliminates the need for the conditional check entirely.