Signup/Sign In

Python Program to Print All Prime Numbers in an Interval

In this tutorial, we will learn how to print all Prime Numbers in a given interval using for loop in Python. The user has to give the upper limit and the lower limit of the interval as input and our program should display all the Prime Numbers within that interval.

A Prime Number is a natural number that is greater than 1 and has only two factors, 1 and the number itself. First, few prime numbers are- 2,3,5,7,11.. and so on. Numbers that are not prime are called composite numbers and have more than 2 factors.

For executing this task our approach will be to run a loop from the lower limit to the upper limit and check each number in this interval if it is prime or not. If you want to know in detail the logic behind how to check if a number is prime or not refer to this tutorial.

The program should take input as follows,

Input- Enter upper limit: 3

Enter lower limit: 10

Output- Prime numbers between 3 and 10 are:

3 5 7


Look at the algorithm below to understand the logic.

Step 1 - Define a function that will check if the number is prime or not

Step 2 - Check whether the number is greater than 1

Step 3 - Run a loop starting from 2 (since 1 is not a prime number) to the number to check for factors

Step 4 - If the number has a factor break out of the loop

Step 5 - Else, print the number

Step 6 - Take input of lower and upper limit from user

Step 7 - Run a loop from lower to the upper limit

Step 8 - Pass each iteration to the function to check and display the number if it is prime

Python Program

Take a look at the code and try to understand it in relation to the algorithm.

def check_prime_no(num):
    if num > 1:
       for i in range(2, num):
           if (num % i) == 0:
           print(num,end=" ")
lower = int(input("enter lower limit: "))
upper = int(input("enter upper limit: "))

print("Prime numbers between", lower, "and", upper, "are:")

for i in range(lower, upper + 1):
   # all prime numbers are greater than 1

enter lower limit: 12
enter upper limit: 37
Prime numbers between 12 and 37 are:
13 17 19 23 29 31 37

We used end=" " to print numbers in a single line


We have learned how to display all the prime numbers between an interval. To execute this task we have defined a function that will check for prime numbers in the interval and print the value accordingly. Then we took inputs from the user and used them to run a loop between the interval. Check, for all the values in the range using the function we defined.