Write a Python Program to Check Prime Number

A prime number is a natural number greater than 1 that has only two factors: 1 and itself. Some examples of prime numbers are 2, 3, 5, 7, 11, 13, etc. In this tutorial, we will write a Python program to check whether a given number is prime or not.

What is a Prime Number?

A number is prime if:

  • It is greater than 1.
  • It is only divisible by 1 and itself.

For example:

  • 5 is prime because it is only divisible by 1 and 5.
  • 8 is not prime because it is divisible by 1, 2, 4, and 8.

Python Program to Check Prime Number

# Taking user input
num = int(input("Enter a number: "))

# A prime number must be greater than 1
if num > 1:
    for i in range(2, int(num ** 0.5) + 1):
        if num % i == 0:
            print(f"{num} is not a prime number.")
            break
    else:
        print(f"{num} is a prime number.")
else:
    print(f"{num} is not a prime number.")

Explanation of the Code

  • The user inputs a number.
  • If the number is less than or equal to 1, it is not a prime number.
  • We iterate from 2 to √num (square root of the number) because any factors will appear within this range.
  • If the number is divisible by any value in this range, it is not prime.
  • Otherwise, it is a prime number.

Output 1

Enter a number: 11
11 is a prime number.

Output 2

Enter a number: 21
21 is not a prime number.

Output 3

Enter a number: 1
1 is not a prime number.
Share your love
Subhankar Rakshit
Subhankar Rakshit

Hey there! I’m Subhankar Rakshit, the brains behind PySeek. I’m a Post Graduate in Computer Science. PySeek is where I channel my love for Python programming and share it with the world through engaging and informative blogs.

Articles: 194