#1 India's Top IT Training Institute
×

About Uncodemy

Know more about who we are and what we stand for.

About Us

About Us

Discover our mission to equip individuals with essential IT skills and industry expertise.

Read More →
UnCodeMy Gallery

UnCodeMy Gallery

Explore highlights from our IT training sessions and success stories.

Read More →
Mentors

Mentors

Meet the industry experts who train and guide you through your course.

Read More →
Free Resources

Free Resources

Free tutorials, interview questions, tools and calculators to help you learn.

Explore →
×

Free Resources

Learn, practice and plan your career — bilkul free.

Tutorials

Tutorials

Step-by-step written tutorials to learn any technology at your own pace.

Read More →
Free Counselling

Free Counselling

Book a free video counselling session and pick the right course for you.

Read More →
Online Compiler

Online Compiler

Write, run and test your code online — no setup required.

Read More →

Python Code to Check Prime Number

A prime number program is one of the first “real” logic problems every Python learner writes. It looks easy, but it teaches loops, conditions, break, functions and even a bit of algorithm thinking.

Blogging Illustration

Prime Number Program in Python (5 Methods with Code and Output)

This guide starts with the simplest method and moves to faster ones. All code was run on Python 3.12.

What is a prime number?

A prime number is a whole number greater than 1 that has exactly two divisors: 1 and itself.

  • Prime: 2, 3, 5, 7, 11, 13, 17, 19 …
  • Not prime: 1 (only one divisor), 4 (divisible by 2), 9 (divisible by 3)

Two facts that help in code:

  • 2 is the only even prime.
  • 0 and 1 are not prime. Many beginner programs forget this.

Method 1: Simple loop (easiest to understand)

Check every number from 2 up to num - 1. If any of them divides num, it is not prime.

num = 29
is_prime = True
if num < 2:
    is_prime = False
else:
    for i in range(2, num):
        if num % i == 0:
            is_prime = False
            break
print(num, "is a prime number" if is_prime else "is not a prime number")

Output

29 is a prime number

To take the number from the user, replace the first line with num = int(input("Enter a number: ")).

break stops the loop as soon as we find a divisor — there is no need to keep checking.

Method 2: Check only up to the square root (much faster)

If n = a × b, one of a or b must be less than or equal to √n. So if nothing up to √n divides n, nothing above it will either.

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 [0, 1, 2, 9, 13, 49, 97]:
    print(n, is_prime(n))

Output

0 False
1 False
2 True
9 False
13 True
49 False
97 True

math.isqrt() returns the whole-number square root (available from Python 3.8). For 97, Method 1 checks 95 numbers; this method checks only 8.

Method 3: Using for-else

Python has a special else block on loops. It runs only if the loop finished without break. This makes the prime check very clean.

n = 21
if n > 1:
    for i in range(2, int(n ** 0.5) + 1):
        if n % i == 0:
            print(n, "is not prime, divisible by", i)
            break
    else:
        print(n, "is prime")
else:
    print(n, "is not prime")

Output

21 is not prime, divisible by 3

This is a nice answer in interviews because it shows you know a Python-specific feature.

Method 4: The 6k ± 1 trick (fast for big numbers)

Every prime greater than 3 is of the form 6k − 1 or 6k + 1. So after removing multiples of 2 and 3, we only test 5, 7, 11, 13, 17, 19 …

def is_prime_fast(n):
    if n < 2:
        return False
    if n in (2, 3):
        return True
    if n % 2 == 0 or n % 3 == 0:
        return False
    i = 5
    while i * i <= n:
        if n % i == 0 or n % (i + 2) == 0:
            return False
        i += 6
    return True

print([x for x in range(1, 50) if is_prime_fast(x)])
print(is_prime_fast(1_000_000_007))

Output

[2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47]
True

1,000,000,007 is a well-known large prime used in competitive programming. This function checks it in a fraction of a second.

Method 5: Sieve of Eratosthenes (all primes up to a limit)

When you need many primes — for example all primes below 10 lakh — checking each number separately is slow. The sieve marks multiples of each prime as “not prime” in one pass.

import math

def sieve(limit):
    is_p = [True] * (limit + 1)
    is_p[0] = is_p[1] = False
    for i in range(2, math.isqrt(limit) + 1):
        if is_p[i]:
            for j in range(i * i, limit + 1, i):
                is_p[j] = False
    return [i for i, ok in enumerate(is_p) if ok]

print(sieve(30))
print(len(sieve(1_000_000)))

Output

[2, 3, 5, 7, 11, 13, 17, 19, 23, 29]
78498

There are 78,498 primes below one million. The sieve finds all of them in well under a second on a normal laptop.

Print all prime numbers from 1 to 100

Using the is_prime() function from Method 2:

primes = [x for x in range(1, 101) if is_prime(x)]
print(primes)
print("Count:", len(primes))

Output

[2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47, 53, 59, 61, 67, 71, 73, 79, 83, 89, 97]
Count: 25

Which method should you use?

Method Best for Speed
1. Simple loop Understanding the logic Slow
2. Square root Most normal programs and exams Fast
3. for-else Clean Python code, interviews Fast
4. 6k ± 1 Very large single numbers Faster
5. Sieve All primes up to a limit Fastest for ranges

A common beginner scenario

Imagine a student testing Method 1 with the numbers 7, 13 and 29. All correct — so the program looks finished. Then a friend types 1, and the program proudly says “1 is a prime number”. The loop range(2, 1) is empty, so the loop never runs and is_prime stays True. One extra check — if num < 2 — fixes it. The lesson: always test edge cases like 0, 1, 2 and a negative number, not only “nice” inputs.

Common mistakes

  • Treating 1 (or 0, or negative numbers) as prime.
  • Writing range(2, n/2) — in Python 3, n/2 is a float and range() will raise a TypeError. Use n // 2 or, better, the square root.
  • Forgetting break, so the loop keeps running after finding a divisor.
  • Using int(math.sqrt(n)) for very large numbers — floating-point rounding can be off by one. math.isqrt() is exact.
  • Printing “prime” inside the loop instead of after it, which prints the message many times.

Practice tasks

  1. Print the first 20 prime numbers (not primes up to 20).
  2. Find the sum of all primes between 1 and 1000.
  3. Print all twin primes (pairs like 11 and 13) below 100.
  4. Write a function that returns the prime factors of a number, e.g. 60 → [2, 2, 3, 5].

Frequently asked questions

Is 1 a prime number?

No. A prime must have exactly two different divisors; 1 has only one.

Is 2 a prime number?

Yes. It is the smallest prime and the only even prime.

Which is the fastest way to check a prime in Python?

For one number, the square-root or 6k ± 1 method. For many numbers in a range, the Sieve of Eratosthenes.

Is there a built-in function for primes in Python?

Not in the standard library. The third-party sympy library has isprime(), but in exams and interviews you are expected to write the logic yourself.

References

Placed Students

Our Clients

Partners