Given a range of numbers, the task is to print all even numbers within that range. An even number is any number that is exactly divisible by 2 (i.e., remainder = 0).
For example:
Range: 1 to 10 -> Even numbers = 2, 4, 6, 8, 10
Range: 5 to 15 -> Even numbers = 6, 8, 10, 12, 14
Let’s explore different methods to print even numbers within a range.
Using range() with Step
The built-in range() function can also be used efficiently to print even numbers by setting a step value of 2. This avoids the need for an extra if condition.
s = 1
e = 10
for i in range(2, e + 1, 2):
print(i)
Output
2 4 6 8 10
Explanation:
- range(2, e + 1, 2) starts from 2 and increases by 2 each time.
- Only even numbers are generated no need for extra checks or conditions.
Using List Comprehension
List comprehension provides a concise way to filter even numbers and print them directly.
s = 1
e = 10
res = [i for i in range(s, e + 1) if i % 2 == 0]
print(res)
Output
[2, 4, 6, 8, 10]
Explanation:
- The expression iterates through all numbers from s to e.
- The condition i % 2 == 0 ensures only even numbers are included in the list.
Using Loop
In this method we iterate through each number in the range and check divisibility by 2 using an if statement.
s = 1
e = 10
for i in range(s, e + 1):
if i % 2 == 0:
print(i)
Output
2 4 6 8 10
Explanation:
- The loop checks each number between s and e.
- If the number gives zero remainder when divided by 2 (i % 2 == 0), it is even and printed.
Related Articles: