Python - Find a Number is Prime or Not

A prime number is a whole number greater than 1 with only two factors - itself and 1.
A prime number can not be divided by another positive integer without leaving a remainder, decimal or fraction.
2,3,5,7,11 etc are the prime numbers as they do not have any other factors.

In this program, you will learn how to find a number is prime or not.


Program Code



    # This program to check if a number is prime or not

    #num = 127
    num = int(input('Enter a Number: '))
    
    if num == 1:
        print(num, "is not a prime number")
    elif num > 1:
        for i in range(2, num):
            if(num % i) == 0:
                print(num, "is not a prime number - ", i, "times",num//i, "is", num)
                break
        else:
            print(num,"is a prime number")
    else:
        print(num, "is not a prime number")

Output



    Enter a Number: 55
    55 is not a prime number -  5 times 11 is 55

In this program, we have used for..else statement to check if the and num is prime or not.

The else part of the for loop execute only if the for loop won't break out.



The following topics can be useful to understand this program.



Related Tutorials