How to Check Whether a Given Number is Prime in Python

A prime number is a natural number greater than 1 which has no positive divisors other than 1 and the number itself. For example, 3 is a prime number since the only positive divisors of 3 are 1 and 3 itself. The number 10 is NOT a prime number since it can be divided by 5 or 2 in addition to 1 and 10. Following are some of the first few prime numbers in the number sequence,

2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41

There are a number of important practical applications of prime numbers such as in the implementation of strong encryption algorithms.

The following python program checks whether a given number is prime or not. It simply goes through all the numbers from 2 to number-1 and checks whether it is a divisor of the number. If one of them is a divisor, we immediately know that the number is not a prime number. We use the else clause of a for loop for printing the prime number status. This else clause is called only if the for loop is completely executed without calling break.

# python 3 code
def is_prime(n):
    for i in range(2,n):
        if n%i == 0:
            return False
    else:
        return True

number = int(input("Please enter a number above 1: "))
if(is_prime(number)):
    print("{} is a prime number".format(number))
else:
    print("{} is NOT a prime number".format(number))

We can easily extend the above program to print all the prime numbers under a given number,

# python 3 code
def is_prime(n):
    for i in range(2,n):
        if n%i == 0:
            return False
    else:
        return True

max_num = int(input("Please enter upper limit for prime numbers: "))
for i in range(2,max_num+1):
    if is_prime(i):
        print(i,end=', ')

Note the use of parameter end in print function to use comma between successive print() calls instead of the default newline.

Do you have a programming problem that you are unable to solve? Please send us your problem and we will publish the solution! Please email us.

Leave a Reply