Python Program To Check Whether The Number Is Prime Or Not

2 min read

A prime number is a positive whole number greater than 1 which is evenly divisible only by 1 and itself. 2, 3, 5, 7, 11, 13 are the first few prime numbers.

Some interesting facts about Prime numbers -

  • 2 is the only even prime number
  • 0 and 1 are not considered as prime numbers
  • Numbers that have more than two factors are called composite numbers.
  • No prime number greater than 5 ends in a 5. Any number greater than 5 that ends in a 5 can be divided by 5.

In this article, we will create a Python program to check whether the given number is Prime or not.

Algorithm To Check Whether A Number Is Prime Or Not

Step 1: Take the input from User

Step 2: Check whether the number is greater than 1, if not than the number is not Prime

Step 3: Check if the number gets evenly divided by any number from 2 to half of the number

Step 4: Print the result

Here we have optimized the algorithm to search only till half of the given number which drastically improves the performance for a very large number.

Python Program To Check Whether The Number Is Prime Or Not

# Taking the input from User
number = int(input("Enter The Number"))

if number > 1:
    for i in range(2,int(number/2)+1):
        if (number % i == 0):
            print(number, "is not a Prime Number")
        print(number,"is a Prime number")
# If the number is less than 1 it can't be Prime
    print(number,"is not a Prime number")


In the given program first, we are taking the input from the user using the input keyword and converting it to integer datatype in case the user inputs a Float number. Next, we are comparing if the number is less than 1 because only a number greater than 1 can be called a Prime number.

Inside the loop, we are diving the number to every number between 2 and the half of the number if no factor is found the number is Prime gets printed out along with the number.

Running the program for the following test cases gave us the expected result.

Enter The Number 2
2 is a Prime number

Enter The Number 11
11 is a Prime number

Enter The Number 9729262
9729262 is not a Prime Number

Enter The Number -20
-20 is not a Prime number

Enter The Number 1
1 is not a Prime number



Latest Articles

Latest from djangocentral

Django 4.1 adds async-compatible interface to QuerySet

The much-awaited pull request for an async-compatible interface to Queryset just got merged into the main branch of Django.Pull Request - The Django core team has been progressively adding async suppor…
Read more →

3 min read

Making Django Admin Jazzy With django-jazzmin

Django admin is undoubtedly one of the most useful apps of Django. Over the years there has been very little change in the admin app as far as the UX is concerned and it's not a bad thing at all. Django admin was designed to provide a simple and minimali…
Read more →

4 min read