Check given number is prime or not in python

In this session, we are going to learn the prime number and how we can check the given number is prime or not using python programming.

what is a prime number

A prime number is a positive integer which is divisible only by itself and 1.
For example: 2,3,5,7……..
the smallest prime number is  2.
Integer 1 is not a prime number.1 is a special number.

You may aslo learn,

Analysis of different  steps to find a prime number in Python

  1. If the given integer is less than equal to 1, it returns  0.
  2. if the given integer is equal to 2, it returns 1.
  3. if the given integer is greater than 2 and the mod between those number and  2 equals to 0, returns 0.
  4. else return 1.

create function prime which returns 0 or 1:

#function which receive integer.
def prime(n):
    if n<=1:
        return 0
    if n==2:
        return 1
    else:
        for i in range(2,n):
            if(n%i)==0:
                return 0
        return 1

Take input from the users :

#type casting string to integer
x=int(input("enter a integer number"))

Call the function prime():

#function call
y=prime(x)

The final condition for checking prime number:

if y==1:
    print("given number is prime number")
else:
    print("given number is not a prime number")

now whole code in a single window :

Python program to check if a number is prime or not

##function which receive integer.
def prime(n):
    if n<=1:
        return 0
    if n==2:
        return 1
    else:
        for i in range(2,n):
            if(n%i)==0:
                return 0
        return 1
#type casting string to integer
x=int(input("enter a integer number "))
#function call
y=prime(x)
if y==1:
    print("given number is prime number")
else:
    print("given number is not a prime number")
    

Output:

enter a integer number 1
given number is not a prime number
enter a integer number 103
given number is prime number
enter a integer number 3
given number is prime number
enter a integer number 2
given number is prime number
enter a integer number21
given number is not prime number

Leave a Reply