Python Practice › If-Else Programs › Program 6
Check a prime number
Write a Python program to check whether a given number is prime.
Input
2, 15, 17, 1
Output
2 is prime 15 is not prime 17 is prime 1 is not prime
Approach
- Numbers below 2 are not prime.
- Try divisors from 2 to the square root; if one divides exactly, it is not prime.
Solution
def is_prime(n): if n < 2: return False for d in range(2, int(n ** 0.5) + 1): if n % d == 0: return False return True for n in [2, 15, 17, 1]: if is_prime(n): print(n, "is prime") else: print(n, "is not prime")Output
2 is prime 15 is not prime 17 is prime 1 is not prime
Line by line
Lines 2-3
0 and 1 are not prime by definition.
Line 4
Checking divisors up to √n is enough.
Lines 5-6
Return early as soon as a divisor is found.
Learn the concept
New to this topic? Read the lesson, then come back.