Python Program to Display or Print Prime Numbers Between a Range or an Interval

In this program, we will learn how to display or print the Prime Numbers between a given range using the Python programming language.

I have already discussed how to check whether a number is prime or not in previous posts. So, check it out for better understanding.

I will be discussing different programs

  • Between an Interval.
  • In Range 1 to N

Python Programming Code to Display or Print Prime Numbers Between a Range or an Interval

In both the programs below, I have used the different approaches in the inner for loop.

In one, I have traversed until half of the number (i/2). And in other, I have traversed till the square root of the number (sqrt(i)).

Between an Interval

In this program, user is asked to give the start and end of the range or interval.

And then I apply the for loop in that range and check every number in between the range including the ends also whether they are a prime number or not.

Code:-

start = int(input("Enter starting number of the interval : "))
end = int(input("Enter ending number of the interval : "))

print("Prime Numbers Between ", start, " and ", end, " : ")
for i in range(start, end+1):
    isPrime = True

    if(i <= 1):
        isPrime = False
    else:
        for j in range(2, int(i/2)):
            if(i % j == 0):
                isPrime = False
                break

    if (isPrime):
        print(i, end=" ")

print()
Enter starting number of the interval : 5
Enter ending number of the interval : 60
Prime Numbers Between 5 and 60 :
5 7 11 13 17 19 23 29 31 37 41 43 47 53 59

In Range 1 to N

In this program, I have asked for only the end of the range.

And then with the help of for loop, numbers are checked.

Code:-

import math

end = int(input("Enter the end of the range : "))

print("Prime Numbers Between 1", " and ", end, " : ")

for i in range(2, end+1):
    isPrime = True

    for j in range(2, int(math.sqrt(i)+1)):
        if(i % j == 0):
            isPrime = False
            break

    if (isPrime):
        print(i, end=" ")

print()

Output:-

Enter the end of the range : 25
Prime Numbers Between 1 and 25 :
2 3 5 7 11 13 17 19 23

You can learn about many other Python Programs Here.

Best Books for learning Python with Data Structure, Algorithms, Machine learning and Data Science.

The following two tabs change content below.
Amit Rawat

Amit Rawat

Founder and Developer at SpiderLabWeb
I love to work on new projects and also work on my ideas. My main field of interest is Web Development.

You may also like...