Important Python Concept

Python Program to Print All Prime Numbers in an Interval/Range

We will learn about the python program to print all prime numbers in a given interval/range. A prime number is a number that is divisible by 1 and itself. For example 2,3,5,7… are said to be prime numbers because all these numbers are divisible by 1 and themselves but not by any other number.

Program

start = int(input("enter the starting value: "))
end = int(input("enter the ending point: "))

print("Prime Numbers in the range are: ")
for n in range(start, end + 1):
    if n > 1:
        for i in range(2, n):
            if (n % i) == 0:
                break
        else:
            print(n)

Output

Prime Numbers in the range are: 
2
3
5
7
11
13
17
19

Explanation

start = int(input("enter the starting value: "))
end = int(input("enter the ending point: "))

Firstly, we need to take the range values from the user as input so that we can find all the prime numbers between that inputted range. The above python statements are used to take the input from the user. Here start represents a variable that takes the starting value of the range and end represents another variable that takes the ending value of the range. The input is of type integer.

for n in range(start,end+1):
   if n > 1:
      for i in  range(2, n):

We have used two for loops and two if loops in the above code. The first for loop is used to move a variable named n from starting point to the ending point. Now we have an if loop inside the first for loop, this if loop will check whether the number is greater than one or not, if yes then control goes to the next for loop, if no then control gets terminated. The second for loop is used to move the variable ‘i’ from 2 to n.

if (n % i) == 0:
  break
else:
  print(n)

This is the main logic of the code. In order to find the prime numbers, we have to perform modular division on each number between the range. If the result of modular division is equal to zero then break and go to the next number. Else if the result of modular division is not equal to zero then it is said to be a prime number and the else part will print that prime number.

Conclusion

We have learned about what is a prime number, how to write a python code to find prime numbers in between a given range, and the logic of the code.

Aniket Malik

Aniket Malik

CERTIFIED TUTOR/TRAINER WITH 300+ REVIEWS

Facing difficulty with

this concept?