Write a program to check Prime number in Python

In this Python example series, we will see how to write program in Python to find prime number. Let’s first see what are prime numbers

Prime numbers are those numbers which are either divided by 1 or by itself, they are not divided by any other number.

Numbers are like 1, 2, 3, 5, 7, 11, 13 etc. are only divided by themselves, that why they are prime numbers.

Now, we understand what are prime numbers, let’s see how to write prime number program in Python programming language.

 

number = int(input("Enter any number: "))  
  
if number > 1:  
   for i in range(2,number):  
       if (number % i) == 0:  
           print(number,"is not a prime number because")    
           print(number,"is divided by",number//i)  
           break  
   else:  
       print(number,"is a prime number")  
         
else:  
   print(number,"is not a prime number")  

Output 1:

Enter any number: 10
10 is not a prime number because
10 is divided by 5

 

Output 2 :

Enter any number: 11
11 is a prime number

 

Explanation:

  • In above example, we are asking to user to put any number.
  • if user put 1, then else part will be executed and we know 1 is prime number, so we will print it.
  • if user put number bigger than 1, then we have introduce for loop here.
  • for loop will start from 2 and will execute till number which user enters -1 , as we have used here range function and range will execute -1 times to the maximum limit number.
  • so, our loop will start iterating and check whether modulus of number is zero or not.
  • if modulus is zero, then its  not a prime number.
READ  Find Square root of a number in Python

 

Please follow and like us: