PythonMastery

Check prime number in Python

Check whether a number is prime by testing divisors only up to its square root. Handles 0, 1 and negative numbers correctly.

A prime number is a whole number greater than 1 that divides only by 1 and by itself. 2, 3, 5, 7 and 11 are prime. 9 is not, because 9 = 3 × 3.

The program

python
import math


def is_prime(n):
    if n < 2:
        return False
    for i in range(2, math.isqrt(n) + 1):
        if n % i == 0:
            return False
    return True


n = int(input("Enter a whole number: "))

if is_prime(n):
    print(f"{n} is a prime number")
else:
    print(f"{n} is not a prime number")

Typed in this example: 97. Press Run to type your own.

output
Enter a whole number: 97
97 is a prime number

How it works

Testing several numbers

python
import math


def is_prime(n):
    if n < 2:
        return False
    for i in range(2, math.isqrt(n) + 1):
        if n % i == 0:
            return False
    return True


for n in [-7, 0, 1, 2, 9, 25, 29]:
    print(n, is_prime(n))
output
-7 False
0 False
1 False
2 True
9 False
25 False
29 True

25 is a good test: its only divisor apart from 1 and 25 is 5, which is exactly its square root. That is why the loop needs the + 1 in math.isqrt(n) + 1.

Related programs: Print prime numbers in a range.

Learn the idea: Functions & Scoping, Loops: for, while, and the Pythonic Patterns