BeginnersBook

  • Home
  • Java
    • Java OOPs
    • Java Collections
    • Java Examples
  • C
    • C Examples
  • C++
    • C++ Examples
  • DBMS
  • Computer Network
  • Python
    • Python Examples
  • More…
    • jQuery
    • Kotlin
    • WordPress
    • SEO
    • JSON
    • JSP
    • JSTL
    • Servlet
    • MongoDB
    • XML
    • Perl

Python Program to Check If a number is Prime or not

Last Updated: January 3, 2018 by Chaitanya Singh | Filed Under: Python Examples

In this post, we will write a program in Python to check whether the input number is prime or not. A number is said to be prime if it is only divisible by 1 and itself. For example 13 is a prime number because it is only divisible by 1 and 13, on the other hand 12 is not a prime number because it is divisible by 2, 4, 6 and number itself.

Checking if number is prime or not

A prime number is always positive so we are checking that in the beginning of the program.

We are dividing the input number by all the numbers in the range of 2 to (number – 1) to see whether there are any positive divisors other than 1 and number itself.

If any divisor is found then we display that the “number is not a prime number” else we display that the “number is a prime number”.

We are using the break statement in the loop to come out of the loop as soon as any positive divisor is found as there is no further check is required.

# taking input from user
number = int(input("Enter any number: "))

# prime number is always greater than 1
if number > 1:
    for i in range(2, number):
        if (number % i) == 0:
            print(number, "is not a prime number")
            break
    else:
        print(number, "is a prime number")

# if the entered number is less than or equal to 1
# then it is not prime number
else:
    print(number, "is not a prime number")

Output:
Python program to check if number is prime or not

Related Posts:

  1. Java Program to check prime number
  2. C++ Program to check prime number
  3. C Program to find prime numbers in a given range
  4. Python Program to check Even or Odd
  5. Python Program to Add two Numbers

Top Related Articles:

  1. Python Program to Check if a Number is Positive Negative or Zero
  2. Python Program to Convert Celsius To Fahrenheit and Vice Versa
  3. Python Program to Check whether Year is a Leap Year or not
  4. Python Program to Find ASCII Value of a Character
  5. Python Program to Check If number is Even or Odd

About the Author

I have 15 years of experience in the IT industry, working with renowned multinational corporations. Additionally, I have dedicated over a decade to teaching, allowing me to refine my skills in delivering information in a simple and easily understandable manner.

– Chaitanya

Leave a Reply Cancel reply

Your email address will not be published. Required fields are marked *

Copyright © 2012 – 2025 BeginnersBook . Privacy Policy . Sitemap