Prime Number Program in Python with Explanation

In this tutorial, we are going to learn how to write a program to check whether a given integer number by the user is a prime number or not in Python programming language.

If a given number is prime then our logic will assign value 0 to a temp variable and will print “number is prime” and if the number is not prime then our logic will assign value 1 to a temp variable program will print “number is not prime”.

Before directly moving on to the writing prime number program in Python Lets know

What is Prime Number?

In Mathematical terms, A prime number is a natural number greater than 1 that can be divided by only 1 and the number itself.

For example 2, 3, 5, 7, 13… are Prime numbers.

Here 2, 3, or any of the above numbers can only be divided by 1 or the number itself. So we can say that numbers are prime numbers.

How our program will behave?

Suppose someone gives an input 2 then our program should give the output “given number is a prime number”.

And if someone gives 4 as an input then our program should give the output “given number is not a prime number”.

There are various methods to write the program. In this post, we will see multiple logics.

Method 1: Check Prime Using For Loop

n = int(input("please give a number : "))
i,temp=0,0
for i in range(2,n//2):
    if n%i == 0:
        temp=1
        break
if temp == 1:
    print("given number is not prime")
else:
    print("given number is prime") 

Output:

please give a number : 23
given number is prime

Leave a Comment