Python Program To Check Prime Number In A Range

Python Program To Check Prime Number In A Range

In this tutorial, you will learn to write a Python program to check prime number in a range

A prime number is a positive integer greater

In other words, a prime number is a number that is only divisible by 1 and itself.

Examples of prime numbers are 2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, and so on.

To understand this program you should have an understanding of the following topics:

  1. For Loop

Python Program To Check Prime Number In A Range

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

print("Prime numbers between", start, "and", end, "are:")

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

Output

Enter the starting number: 0
Enter the ending number: 50
Prime numbers between 0 and 50 are:
2 3 5 7 11 13 17 19 23 29 31 37 41 43 47

In this program, we first prompt the user to enter the starting and ending numbers of the range to check for prime numbers.

We then loop through all the numbers within that range using the range() function.

For each number in the range, we check whether it is greater than 1 (since 1 is not a prime number).

If the number is greater than 1, we then loop through all the numbers from 2 to num-1, checking whether num is divisible by any of them.

If the number is divisible by any of them, we break out of the loop.

In case we loop through all the numbers without finding a divisor, then num is a prime number and we print it.

Note that we use the else statement with the for loop to print a number only if we loop through all the numbers without finding a divisor.

If we find a divisor, we skip the else statement and continue with the next number in the range.


Discover more from Python Mania

Subscribe to get the latest posts sent to your email.

0 0 votes
Article Rating
Subscribe
Notify of
0 Comments
Most Voted
Newest Oldest
Inline Feedbacks
View all comments

Related Articles:

Recent Articles:

0
Would love your thoughts, please comment.x
()
x

Discover more from Python Mania

Subscribe now to keep reading and get access to the full archive.

Continue reading