Let’s write a Python program to check if number is prime or not.

What is a Prime number?

A number which is not divisible by any number except 1 and itself is called as a prime number. A prime number has only two factors, 1 and itself.

How to check if number is prime?

To check if a given number (N) is a prime number or not, check if the number has any factor other than 1 and itself. Let’s create a loop which iterates from 2 to N-1 to check for divisibility. If given number (N) is not divisible by any of the numbers, then it is declared as a prime number. If the number is divisible by any of the numbers between 2 to N-1, it is declared as non-prime.

Python Code (using while loop)

The Python program given below checks if number is prime or not using a while loop.

#Python program to check if number is prime or not
n = int(input("Enter a number "))
prime=True
i=2
while i<n:
    if n%i == 0:
        prime = False
        break
    i = i + 1
if prime:
    print("The given number is prime.")
else:
    print("The given number is non-prime.")    

Python program (using while loop with else block)

The code can be improved further by using else block with the while loop as given below.

#Python program to check if a number is prime or not
n = int(input("Enter a number "))
i=2
while i<n:
    if n%i == 0:
        print("The given number is non-prime.")    
        break
    i = i + 1
else:
    print("The given number is prime.")

Python program (using functions)

The code can be written as a function which returns True or False depending on the number.

#Function to check if a number is prime or not
def isPrime(n):
    i=2
    while i<n:
        if n%i == 0:
            return False    #number is not a prime number
            break
        i = i + 1
    else:
        return True         #number is a prime number
    
#code to test the above function
n = int(input("Enter a number "))
if isPrime(n):
    print("The given number is prime.")    
else:
    print("The given number is non-prime.")    
Last modified: March 27, 2023

Author