Prime Numbers in Python: Check a Number and Print Prime Series

A prime number is an integer greater than 1 with exactly two positive divisors: 1 and itself. For example, 2, 3, 5, 7 and 11 are prime; 1 is not prime.

Interactive Companion Jupyter Notebook

Run the Python examples, compare expected outputs, modify the code, and complete guided exercises.

View on GitHub Open in Google Colab
On this page — Show page sections— Hide page sections

First working example

n = 50
for value in range(2, n + 1):
    prime = True
    for divisor in range(2, value):
        if value % divisor == 0:
            prime = False
            break
    if prime:
        print(value, end=" ")

Output:

2 3 5 7 11 13 17 19 23 29 31 37 41 43 47 

This retains the original nested-loop idea and correctly starts at 2.

Original half-range technique

The original lesson checks candidate divisors up to half of each number. It is correct for integers at least 2 but does more work than necessary.

n = 50
for i in range(2, n + 1):
    flag = 0
    for j in range(2, i // 2 + 1):
        if i % j == 0:
            flag = 1
            break
    if flag == 0:
        print(i, end=", ")

Output:

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

Check if a single number is prime

Always handle 0, 1 and negative values explicitly; otherwise a loop may never run and mislabel them prime.

n = int(input("Enter number: "))
if n < 2:
    print("Not prime")
else:
    for i in range(2, n):
        if n % i == 0:
            print("Not prime")
            break
    else:
        print("Prime")

Output:

Not prime

Faster primality test with math.isqrt()

If a composite integer has any divisor, one of its divisors is at most its square root.

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

for n in (0, 1, 2, 17, 25, 97):
    print(n, is_prime(n))

Output:

0 False
1 False
2 True
17 True
25 False
97 True

Use a count to stop after the requested number of prime values, rather than at a numeric upper limit.

from math import isqrt
def is_prime(n):
    return n >= 2 and all(n % d for d in range(2, isqrt(n) + 1))
count = 0
value = 2
while count < 10:
    if is_prime(value):
        print(value, end=" ")
        count += 1
    value += 1

Output:

2 3 5 7 11 13 17 19 23 29 

Generate primes in a range

A reusable function can power a range query.

from math import isqrt
def is_prime(n):
    return n >= 2 and all(n % d for d in range(2, isqrt(n) + 1))
primes = [n for n in range(20, 51) if is_prime(n)]
print(primes)

Output:

[23, 29, 31, 37, 41, 43, 47]

Use the Sieve of Eratosthenes

For a large list of primes up to one limit, sieve candidates once rather than retesting every candidate independently.

limit = 40
sieve = [True] * (limit + 1)
sieve[0:2] = [False, False]
for p in range(2, int(limit ** 0.5) + 1):
    if sieve[p]:
        for multiple in range(p * p, limit + 1, p):
            sieve[multiple] = False
print([n for n, prime in enumerate(sieve) if prime])

Output:

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

Common mistakes and troubleshooting

  • Run each example in Python 3.9 or newer. Indentation is significant in loops and functions.
  • Remember that input() returns a string. Convert and validate the value before doing arithmetic.
  • Check boundary values such as zero, negative numbers, small inputs and empty ranges.
  • When comparing outputs, note whether a code sample uses fixed values or user input.

Practice exercises

Compare the test counts for a 4-digit prime using the simple and square-root methods. Use the companion practice notebook for runnable examples and self-checks.

Frequently asked questions

Is 1 a prime number?

No, it has only one positive divisor.

Is 2 a prime number?

Yes. It is the only even prime number.

Why stop at the square root?

A factor larger than the square root has a matching factor smaller than it.

Plus2Net Python Basics podcast playlist

Other related resources

Back to top ↑




Subscribe to our YouTube Channel here



plus2net.com




Python Video Tutorials
Python SQLite Video Tutorials
Python MySQL Video Tutorials
Python Tkinter Video Tutorials
✖
We use cookies to improve your browsing experience. . Learn more
HTML MySQL PHP JavaScript ASP Photoshop Articles Contact us
© 2000-2026 plus2net.com All rights reserved worldwide Privacy Policy Disclaimer