Open In App

Python program to print all even numbers in a range

Last Updated : 29 Nov, 2024
Summarize
Comments
Improve
Suggest changes
Like Article
Like
Share
Report
News Follow

In this article, we will explore various methods to print all even numbers in a range. The simplest way to do is by using a loop.

Using Loop

We can use a for loop with if conditional to check if a number is even.

start = 1
end = 10

# Using a for loop to print even numbers
for i in range(start, end + 1):
    if i % 2 == 0:
        print(i)

Output
2
4
6
8
10

Explanation:

  • We loop through all the numbers in the given range (start to end).
  • The condition i % 2 == 0 checks if the number is even (i.e., divisible by 2).
  • If the condition is True than print the number.

Let’s explore other different method to print all even numbers in a range:

Using List Comprehension

List comprehension provides a concise way to filter even numbers and print them directly.

start = 1
end = 10

# Using list comprehension to find even numbers
res = [i for i in range(start, end + 1) if i % 2 == 0]

# Printing the list of even numbers
print(res)

Output
[2, 4, 6, 8, 10]

Explanation:

  • This list comprehension generates a list of numbers from start to end where i % 2 == 0 (i.e., the number is even).
  • The result is a list of even numbers which is then printed.

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.

start = 1
end = 10

# Using range() with step to print even numbers
for i in range(2, end + 1, 2):
    print(i)

Output
2
4
6
8
10

Explanation:

  • The range(2, end + 1, 2) generates numbers starting from 2 and increments by 2, this producing only even numbers.
  • No need for an if condition as the range is already defined to only include even numbers.


Next Article

Similar Reads

three90RightbarBannerImg