Python Program to Print all Prime Numbers in an Interval

In this post, we will learn how to print all prime numbers lying in an interval using the Python Programming language.

Prime numbers are the natural numbers greater than 1, that have only two factors – 1 and the number itself. For example – 2, 3, and 7 are prime numbers whereas 9 is not a prime number because 3 x 3 = 9.

The below program asks the user to enter the lower and upper limit of the interval, then it prints all the prime numbers lying in that range.

So, without further ado, let’s begin this tutorial.

Python Program to Print all Prime Numbers in an Interval

# Python Program to Print all Prime Numbers in an Interval

# Asking for input
lower = int(input("Enter the lower limit of the range: "))
upper = int(input("Enter the upper limit of the range: "))

print("Prime numbers from ", lower ," to ", upper ," are: ")
for num in range(lower, upper + 1):
    if num > 1:
        for i in range(2, num):
            if (num % i == 0):
                break
        else:
            print(num)

Output

Enter the lower limit of the range: 600
Enter the upper limit of the range: 700
Prime numbers from  600  to  700  are: 
601
607
613
617
619
631
641
643
647
653
659
661
673
677
683
691

How Does This Program Work?

lower = int(input("Enter the lower limit of the range: "))
upper = int(input("Enter the upper limit of the range: "))

The user is asked to enter the lower and upper limits of the interval. These values get stored in the lower and upper named variables.

for num in range(lower, upper + 1):
    if num > 1:
        for i in range(2, num):
            if (num % i == 0):
                break
        else:
            print(num)

Now, we use a for loop to print all the prime numbers lying in the given range. For each iteration, we check whether the num is divisible by different iterations of i or not.

If yes, then that means num contains factors other than 1. In that case, num is not a prime number. 

Conclusion

I hope after going through this post, you understand how to print all prime numbers lying in an interval using the Python Programming language.

If you have any doubt regarding the program, then contact us in the comment section. We will be delighted to assist you.

Also Read:

Leave a Comment

Your email address will not be published. Required fields are marked *