Signup/Sign In

Python Program to Check for Prime Number

In this tutorial, you will learn how to check if a number is prime or not using Python Programing language. Our program should take a number given by the user and display if it is prime or not.

A Prime Number is a natural number that is greater than 1 and has only two factors, 1 and the number itself. First, few prime numbers are- 2,3,5,7,11.. and so on. Numbers that are not prime are called composite numbers and have more than two factors. We will follow this approach and find if a number has more than two factors or not to decide if it is prime.

We will use for loop and if-else conditional statements for executing this program. Before moving further it is necessary that you have some knowledge about conditional statements in Python. For example,

The program should take the following as input and give output accordingly,

Input- Enter number: 4

Output- 4 is not prime

Algorithm

Take a look at the algorithm of this program to understand the logic behind the program.

Step 1 - Define a function check_prime_no() which will check if the number is prime or not

Step 2- Run a loop from 2 to the number to find if the number has more than two factors

Step 3 - To find the factor simply check for divisibility, if it is a factor then it will divide the number completely leaving 0 as the remainder

Step 4 - if you find a factor print "Number is not prime" and break out of the loop

Step 5 - else, print that the "Number is prime"

Step 6 - Take input of a number from the user

Step7 - Check if it is greater than 1

Step 8 - if,yes pass the number in the function check_prime_no() as parameter

Step 9 - else, print "1 is neither prime nor composite"

Python Program

Look at the complete program given below to understand the implementation of the approach.

#Check if prime number

#function definition
def check_prime_no(num):
       for i in range(2, num):
           if (num % i) == 0:
             print("{} is not Prime".format(num))
             break
       else:
           print("{} is Prime".format(num))

#input    
n = int(input("enter number "))
if n>1: 
 check_prime_no(n)
else:
 print("1 is neither prime nor composite")


enter number 56
56 is not Prime

enter number 103
103 is Prime

The format() is a function for handling strings that permits you to do variable substitutions and data formatting. Here we have used this function to print the value of num. This function will print the value where {} is present.

Conclusion

In this tutorial, we learned to check if a number is prime or not using Python. We have used the concept of loops, conditional statements, and breaks to execute this task. To take the controller out of the loop we have used the keyword break. We have also checked if the number is greater than 1 or not before passing the value to the defined function.