Python Program to Check Prime Number (5 Tested Ways)

Is 2027 prime? A teammate asked us that while testing a date script, and we had to check.

Quick answer: a Python program to check prime number values tests divisors from 2 to the square root. No even division, and above 1? It’s prime:

def is_prime(n):
    return n > 1 and all(n % d for d in range(2, math.isqrt(n) + 1))

In this tutorial, we’ll write a Python program to check prime number inputs as a function, with typed input, for…else, 6k +/- 1 and SymPy.

What You Need Before You Start Checking Primes

Python 3.8+ (for math.isqrt()) and pip install sympy. I ran everything on Python 3.12.5 and SymPy 1.14.0.

Step 1: Write an is_prime() function in Python

A prime is above 1 and divisible only by 1 and itself. We test our sample numbers in a for loop in Python:

import math

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

for n in [1, 2, 17, 21, 25, 97, 2026, 2027]:
    print(f"{n:>5}: {is_prime(n)}")

Output:

    1: False
    2: True
   17: True
   21: False
   25: False
   97: True
 2026: False
 2027: True
Command Prompt output of a Python is_prime function checking 1, 2, 17, 21, 25, 97, 2026 and 2027
Only 2, 17, 97 and 2027 come back True; 25 is caught by its square root, 5.

Any divisor above the square root pairs with one below it, so 2027 needs 44 checks, not 2,025.

Step 2: Check a number the user types

Users type words, so we loop until input() gets digits:

# is_prime() from Step 1

while True:
    text = input("Enter a whole number: ").strip()
    if text.lstrip("-").isdigit():
        break
    print("  That's not a whole number. Try again.")

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

Output:

Enter a whole number: twenty
  That's not a whole number. Try again.
Enter a whole number: 2027
2027 is a prime number.
Command Prompt run of a Python program that rejects the word twenty, then reports that 2027 is a prime number
The word twenty is rejected, and 2027 comes back as a prime number.

The Python all() function stops at the first divisor with no remainder, like Step 1’s loop.

Step 3: Check primes with for…else

In for...else, the else runs only if the loop never exits early. We return the factor pair when one turns up:

import math

def check(n):
    for d in range(2, math.isqrt(n) + 1):
        if n % d == 0:
            return f"{n} = {d} x {n // d}"
    else:
        return f"{n} is prime" if n > 1 else f"{n} is not prime"

for n in [1, 21, 25, 2026, 2027]:
    print(check(n))

Output:

1 is not prime
21 = 3 x 7
25 = 5 x 5
2026 = 2 x 1013
2027 is prime

So 2026 = 2 x 1013, while 2027 reaches the else.

Step 4: Speed up the check with a while loop and 6k +/- 1

Primes above 3 sit next to multiples of 6, so this while loop in Python tests only d and d + 2:

def is_prime_6k(n):
    if n < 4:
        return n > 1
    if n % 2 == 0 or n % 3 == 0:
        return False
    d = 5
    while d * d <= n:
        if n % d == 0 or n % (d + 2) == 0:
            return False
        d += 6
    return True

print(is_prime_6k(2026), is_prime_6k(2027))
print(is_prime_6k(999_999_999_989))   # largest 12-digit prime

Output:

False True
True
Command Prompt output of a 6k +/- 1 prime check on 2026, 2027 and 999,999,999,989
The 6k +/- 1 check rejects 2026 and confirms 2027 and the largest 12-digit prime.

It needs about a sixth of Step 1’s loop passes. For a whole list, use the Python program to print prime numbers.

Prime check methods in Python: cheat sheet

MethodBest for
for loop + math.isqrt()Learning, everyday checks
for…elseShowing the factor
while loop, 6k +/- 1Up to about 15 digits
sympy.isprime()Huge numbers

Is there a built-in function to check prime numbers in Python?

Not in the standard library, but SymPy’s isprime() goes far beyond trial division:

from sympy import isprime, nextprime

print("2027:", isprime(2027))
print("2**127 - 1:", isprime(2**127 - 1))    # 39 digits
print("2**127 + 1:", isprime(2**127 + 1))
print("Next prime after 2026:", nextprime(2026))

Output:

2027: True
2**127 - 1: True
2**127 + 1: False
Next prime after 2026: 2027
Command Prompt output of SymPy isprime confirming 2027 and the Mersenne prime 2**127 - 1, and nextprime after 2026
SymPy confirms the 39-digit 2**127 – 1 and rejects 2**127 + 1.

We cover nextprime() in finding the next largest prime number in Python; SymPy can also generate a random prime number.

Common Mistakes to Avoid in a Python prime check

We reproduced two classic bugs: no check below 2, and a range that stops before the root:

def is_prime_buggy(n):
    for d in range(2, int(n ** 0.5)):
        if n % d == 0:
            return False
    return True

for n in [1, 4, 25, 49]:
    print(n, is_prime_buggy(n))

Output:

1 True
4 True
25 True
49 True

Add if n < 2 and loop to math.isqrt(n) + 1; n ** 0.5 is a float (see square root in Python).

Next Steps after checking a prime number in Python

Next, find prime numbers in a range using Python or add them up with the sum of prime numbers in a range.

We’d practice these number programs next:

Frequently asked questions

How do you check if a number is prime in Python?

Return False below 2, then test divisors from 2 to math.isqrt(n).

Is 1 a prime number?

No. A prime needs exactly two divisors.

Why check divisors only up to the square root?

Each factor above the root pairs with one below it.

Is 2 a prime number?

Yes, the only even prime.

What’s the fastest way to check a large prime in Python?

sympy.isprime(); without libraries, the 6k +/- 1 loop.

Where is math.isqrt() documented?