Python Program to Check a Prime Number
Beginner · Numbers · CBSE class 11 practical list · CBSE class 12 practical list
A prime number is a whole number greater than 1 that can only be divided evenly by 1 and itself, like 2, 3, 5, 7 and 29. Numbers greater than 1 that are not prime are called composite. This program checks whether a number is prime by looking for any divisor.
Program
prime_number.py
num = 29 # or: num = int(input("Enter a number: "))
if num < 2:
print(num, "is neither prime nor composite")
else:
is_prime = True
# A divisor larger than the square root would pair with a smaller one,
# so checking up to the square root is enough.
for i in range(2, int(num ** 0.5) + 1):
if num % i == 0:
is_prime = False
break
if is_prime:
print(num, "is a prime number")
else:
print(num, "is a composite number")
Output
29 is a prime number
How it works
- Numbers below 2 are handled first, because 0 and 1 are neither prime nor composite.
- The loop tries every divisor from 2 up to the square root of
num. - If
num % i == 0for anyi, the number has a divisor, so it is not prime and the loop stops withbreak. - If no divisor is found,
is_primestaysTrueand the program reports a prime number.
Another way to write it
Using a function
Using a function
def is_prime(n):
if n < 2:
return False
for i in range(2, int(n ** 0.5) + 1):
if n % i == 0:
return False
return True
for n in [2, 9, 17, 25, 29]:
print(n, "prime" if is_prime(n) else "not prime")
Output
2 prime 9 not prime 17 prime 25 not prime 29 prime
Putting the check in a function lets you test many numbers at once.
Try it yourself
Change the program to print every prime number between 1 and 50.
Edit the program above and press Run, or open it in the full editor to save it and share it. To watch it run line by line, open it in the visualizer.
Related programs
All Python programs · CBSE class 12 practical file · Python exercises