PythonMastery

Print prime numbers in a range in Python

Print all prime numbers between two numbers with a loop, and find every prime up to a limit faster with the Sieve of Eratosthenes.

This program prints every prime number between a start and an end value. It reuses the is_prime() function from the prime number check page.

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


start = int(input("Start: "))
end = int(input("End: "))

primes = [n for n in range(start, end + 1) if is_prime(n)]

print(f"Primes from {start} to {end}:", *primes)
print("Count:", len(primes))

Typed in this example: 10, 50. Press Run to type your own.

output
Start: 10
End: 50
Primes from 10 to 50: 11 13 17 19 23 29 31 37 41 43 47
Count: 11

How it works

Another way: the Sieve of Eratosthenes

To find all primes up to a limit, the Sieve of Eratosthenes is much faster than testing each number. It starts by marking every number as possibly prime. Then, for each prime it finds, it crosses out all multiples of that prime.

python
limit = 50

is_prime = [True] * (limit + 1)
is_prime[0] = is_prime[1] = False

for n in range(2, int(limit ** 0.5) + 1):
    if is_prime[n]:
        for multiple in range(n * n, limit + 1, n):
            is_prime[multiple] = False

primes = [n for n in range(limit + 1) if is_prime[n]]
print(*primes)
output
2 3 5 7 11 13 17 19 23 29 31 37 41 43 47

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