Skip to content
Related Articles

Related Articles

Python program to print all even numbers in a range

View Discussion
Improve Article
Save Article
  • Difficulty Level : Easy
  • Last Updated : 03 Aug, 2022

Given starting and end points, write a Python program to print all even numbers in that given range. Example:

Input: start = 4, end = 15
Output: 4, 6, 8, 10, 12, 14

Input: start = 8, end = 11
Output: 8, 10

Example #1: Print all even numbers from given list using for loop Define start and end limit of range. Iterate from start till the range in the list using for loop and check if num % 2 == 0. If the condition satisfies, then only print the number. 

Python3




for num in range(4,15,2):
  #here inside range function first no dentoes starting, second denotes end and third denotes the interval
    print(num)

Output:

4 6 8 10 12 14 

  Example #2: Taking range limit from user input 

Python3




# Python program to print Even Numbers in given range
 
start = int(input("Enter the start of range: "))
end = int(input("Enter the end of range: "))
 
# iterating each number in list
for num in range(start, end + 1):
     
    # checking condition
    if num % 2 == 0:
        print(num, end = " ")

Output:

Enter the start of range: 4
Enter the end of range: 10
4 6 8 10 

Example#3 Taking range limit user input and uses skip sequence number in range function which generate the all even number. 

Python3




# Python program to print Even Numbers in given range
 
start = int(input("Enter the start of range: "))
end = int(input("Enter the end of range: "))
 
#creating even starting range
start = start+1 if start&1 else start
  
 
#create a list and printing element
#contains Even numbers in range
[ print( x ) for x in range(start, end + 1, 2)]

Output:

Enter the start of range: 4
Enter the end of range: 10
4 6 8 10 

Method: Using recursion 

Python3




def even(num1,num2):
    if num1>num2:
        return
    print(num1,end=" ")
    return even(num1+2,num2)
num1=4;num2=15
even(num1,num2)

Output

4 6 8 10 12 14 

Method: Using the lambda function 

Python3




# Python code To print all even numbers
# in a given range using the lambda function
a=4;b=15
li=[]
for i in range(a,b+1):
    li.append(i)
# printing odd numbers using the lambda function
even_num = list(filter(lambda x: (x%2==0),li)) 
print(even_num)

Output

[4, 6, 8, 10, 12, 14]

Method: Using list comprehension 

Python3




x=[i for i in range(4,15+1) if i%2==0]
print(*x)

Output

4 6 8 10 12 14

My Personal Notes arrow_drop_up
Recommended Articles
Page :

Start Your Coding Journey Now!