Python programs · Numbers
Python program to check a prime number
A prime number has exactly two divisors: 1 and itself. To test one, try dividing it by smaller numbers.
Approach
- Numbers below 2 are not prime.
- Try every divisor from 2 up to the square root of the number.
- If one divides it exactly, the number is not prime, so stop early with
break.
The program
n = int(input()) if n < 2: prime = False else: prime = True for i in range(2, int(n ** 0.5) + 1): if n % i == 0: prime = False break print(n, "is prime" if prime else "is not prime")
Sample run
Input
29
Output
29 is prime
How the code works
Only divisors up to the square root need checking, because divisors come in pairs: if n = a × b, one of the two is at most the square root. That keeps the loop short. For a number near ten million you check about 3,162 divisors instead of ten million. break leaves the loop as soon as a divisor is found.
Try changing it
- Print all primes up to 50 by putting this test inside another loop.
- Wrap the test in a function
is_prime(n)that returnsTrueorFalse.
Common mistakes
- Treating 1 as prime. It has only one divisor.
- Starting the divisor loop at 1, which divides every number and makes all numbers look not prime.