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 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:-
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.
Amit Rawat
Latest posts by Amit Rawat (see all)
- Python Program to Print the Fibonacci Sequence (2 ways) - April 7, 2020
- Python Program to Display or Print Prime Numbers Between a Range or an Interval - June 18, 2019
- Python Program To Print Pascal’s Triangle (2 Ways) - June 17, 2019