FREE E LEARNING PLATFORM
HOMEEXCEPTIONSOOPSJVMINTRO
 

Program to Check If a number is Prime or not




In this post, we will write a program in Python to check whether the input number is prime or not. A number is said to be prime if it is only divisible by 1 and itself. For example 13 is a prime number because it is only divisible by 1 and 13, on the other hand 12 is not a prime number because it is divisible by 2, 4, 6 and number itself.

Checking if number is prime or not

A prime number is always positive so we are checking that in the beginning of the program.

We are dividing the input number by all the numbers in the range of 2 to (number - 1) to see whether there are any positive divisors other than 1 and number itself.

If any divisor is found then we display that the "number is not a prime number" else we display that the "number is a prime number".

We are using the break statement in the loop to come out of the loop as soon as any positive divisor is found as there is no further check is required.

# taking input from user
number = int(input("Enter any number: "))

# prime number is always greater than 1
if number > 1:
    for i in range(2, number):
        if (number % i) == 0:
            print(number, "is not a prime number")
            break
    else:
        print(number, "is a prime number")

# if the entered number is less than or equal to 1
# then it is not prime number
else:
    print(number, "is not a prime number")

Output

Enter any number: : 11
11 is a prime number






Leave Comment