Python Program To Check Prime Number Using While Loop

Python Program To Check Prime Number Using While Loop

In this tutorial, you will learn to write a Python Program To Check Prime Number Using While Loop.

A prime number is a positive integer greater than 1 that has no positive integer divisors other than 1 and itself.

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. While Loop

Python Program To Check Prime Number Using While Loop

n = int(input("Enter a number: "))

if n < 2:
    print(n, "is not a prime number")
else:
    i = 2
    while i*i <= n:
        if n % i == 0:
            print(n, "is not a prime number")
            break
        i += 1
    else:
        print(n, "is a prime number")

Output

Enter a number: 47
47 is a prime number

In this program, we first prompt the user to enter a number.

If the number is less than 2, we immediately print that it is not prime and exit the program.

If the number is greater than or equal to 2, we initialize a variable i to 2 and enter a while loop.

The loop will continue as long as i*i is less than or equal to n.

Within the loop, we check whether n is divisible by i.

If it is, we print that the number is not prime and break out of the loop.

If it is not divisible by i, we increment i by 1 and continue with the loop.

If we exit the loop without finding a divisor, then n is a prime number and we print that the number is prime.

Note that we use the else statement with the while loop to print a number only if we loop through all the values of i without finding a divisor.

If we find a divisor, we skip the else statement and exit the loop.

Was this helpful?
YesNo

Related Articles:

Recent Articles:

5 1 vote
Article Rating
Subscribe
Notify of
0 Comments
Inline Feedbacks
View all comments
0
Would love your thoughts, please comment.x
()
x