Prime Number Program in Python

Write a Program to get a number n and to find whether n is prime number or not. Generally Prime number is a number which cannot be divisible by any whole numbers except 1 and n.

Sample Input 1:

9

Sample Output 1:

Not a Prime Number

Sample Input 2:

11

Sample Output 2:

Prime Number

Note : 

9 is divisible by 3

11 is only divisible by 1 and 11.


Try your Solution

Strongly recommended to Solve it on your own, Don't directly go to the solution given below.

#write your code here

Program or Solution

				
				
					

#Python Program to find whether given number is Prime or Not

n = int(input("Enter a Number:")) #get input n


#check which are the numbers from 2 to n/2 divides n.

#No other after n/2 divides n except n

for i in range(2,n//2+1):

    if n % i == 0: #if divisible then it is not prime.

        print("It is Not a Prime Number")

        break

else: #this is else of for  statement. executes after last iteration if loop is not broken at any iteration.

    print("It is a Prime Number")

Program Explanation

input() gets the value of n from users as string, and int() coverts the same to integer. 

The following for loop iterates from i = 1 to n/2, in each iteration it checks whether the n is divisible by i.

if i divides n then print "It is Not a Prime" and exit the loop through break statement. No other number after n/2 divides n except n.

Print "It is a Prime Number" after last iteration if loop iteration was not broken at any iteration.

Comments


Related Programs