Python 3 program to print all even numbers in a range:
In this example, we will learn how to print all the even numbers in a given range. Even number is a number that is perfectly divisible by 2. Steps we are going to use in this program are as below :
Steps to find even numbers in a range :
1. Take lower limit and upper limit from the user.
2. Run one loop from lower limit to upper limit .
3. Check for each number if it is divisible by 2 or not.
4. If it is divisible by 2, print out the number.
Python 3 Program :
lower_limit = int(input("Enter the lower limit : ")) upper_limit = int(input("Enter the upper limit : ")) for i in range(lower_limit,upper_limit+1): if(i%2 == 0): print(i)
Sample Output :
Enter the lower limit : 1 Enter the upper limit : 10 2 4 6 8 10
1. User input is taken using ‘input()’ method. As this is a number, it is converted to an integer using ‘int(input())‘ method.
2. Lower limit is stored in ‘lower_limit‘ variable and upper limit is saved in ‘upper_limit‘ variable.
3. We used a ‘for‘ loop to iterate between the numbers.
4. ‘for i in range(lower_limit,upper_limit+1)‘ means the loop will run from ‘lower_limit‘ to ‘upper_limit‘. e.g. if ‘lower_limit‘ is 1 and ‘upper_limit‘ is 3, loop will run for i=1, i=2 and i=3.
5. Inside the loop, we are checking if the number is divisible by 2 or not. For that, we are using ‘i%2′. ‘%’ or ‘modulo‘ operator returns the reminder . If the number is perfectly divisible by 2, it will return ‘0’.
6. If the number is perfectly divisible by 2, print the number.