Python Program to Print Prime Numbers (1 to 100, 1 to N, First N)

A prime number is a whole number greater than 1 that can only be divided evenly by 1 and itself. To print prime numbers in Python, loop over the numbers and test each one for a divisor between 2 and its square root; if there is none, the number is prime. This page has ready-to-run programs for every common version of the task: primes from 1 to 100, from 1 to N (user input), the first N primes, primes in a range, with for and while loops, a one-liner, the fast Sieve of Eratosthenes and the SymPy library.

Every program was run with Python 3.12.5 (SymPy 1.14.0), and the output below is copied from the terminal.

Python program to print prime numbers from 1 to 100

import math

def is_prime(n):
    """Return True if n is a prime number."""
    if n < 2:
        return False
    for divisor in range(2, math.isqrt(n) + 1):   # only up to the square root
        if n % divisor == 0:
            return False
    return True

primes = [n for n in range(1, 101) if is_prime(n)]
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
Command Prompt screenshot: the Python program to print prime numbers from 1 to 100 and its output, the 25 primes from 2 to 97 and Count: 25
The program and its real output in the Windows Command Prompt.

How it works: is_prime() returns False for numbers below 2, then tries every divisor from 2 up to math.isqrt(n) (the whole-number square root). If any of them divides n exactly (n % divisor == 0), n is not prime. The list comprehension keeps the numbers for which is_prime() is True. math.isqrt() (Python 3.8+) is described in the official math module documentation.

Why only up to the square root?

If n = a × b, one of the two factors is always at most √n. For 91 = 7 × 13, the divisor 7 is found before reaching √91 ≈ 9.5, so checking 10, 11, 12… is wasted work. For a prime like 97 the loop stops after 9 instead of 95.

Check if a number is prime

The same is_prime() function answers “is this number prime?” for a single number:

import math

def is_prime(n):
    """Return True if n is a prime number."""
    if n < 2:
        return False
    for divisor in range(2, math.isqrt(n) + 1):   # only up to the square root
        if n % divisor == 0:
            return False
    return True


number = int(input("Enter a number: "))
if is_prime(number):
    print(number, "is a prime number")
else:
    print(number, "is not a prime number")

Output for 97, 91 and 1:

Enter a number: 97
97 is a prime number
Enter a number: 91
91 is not a prime number
Enter a number: 1
1 is not a prime number

91 looks prime but is 7 × 13. The n < 2 check makes 1 (and 0 and negative numbers) come out as not prime. For a full guide to testing a single number, see Python program to check prime numbers.

Prime numbers from 1 to 100: the list

Chart of the numbers 1 to 100 with the 25 prime numbers highlighted in blue: 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
The 25 prime numbers between 1 and 100, highlighted.
RangePrime numbersCount
1–102, 3, 5, 74
1–202, 3, 5, 7, 11, 13, 17, 198
1–502, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 4715
1–1002, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47, 53, 59, 61, 67, 71, 73, 79, 83, 89, 9725

2 is the only even prime. 1 is not a prime number, because it has only one divisor.

Print prime numbers using a for loop

Without a helper function, use a nested for loop with an else clause. The else of a for loop runs only if the loop finished without break, which is exactly “no divisor was found”:

# Prime numbers from 1 to 100 using a for loop (no function)
for num in range(2, 101):
    for divisor in range(2, num):
        if num % divisor == 0:
            break                 # found a divisor: not prime
    else:
        print(num, end=" ")      # the loop finished without break: prime

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

This version is the easiest to read but checks every divisor up to num - 1. That’s fine for 100 numbers; for larger ranges use the square-root check or the sieve below.

Print prime numbers using a while loop

# Prime numbers from 1 to 100 using a while loop
num = 2
while num <= 100:
    divisor = 2
    is_prime = True
    while divisor * divisor <= num:
        if num % divisor == 0:
            is_prime = False
            break
        divisor += 1
    if is_prime:
        print(num, end=" ")
    num += 1

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

divisor * divisor <= num is the square-root check without importing math.

Print prime numbers from 1 to N (user input)

import math

def is_prime(n):
    """Return True if n is a prime number."""
    if n < 2:
        return False
    for divisor in range(2, math.isqrt(n) + 1):   # only up to the square root
        if n % divisor == 0:
            return False
    return True


n = int(input("Print prime numbers up to: "))
primes = [num for num in range(2, n + 1) if is_prime(num)]
print(f"There are {len(primes)} prime numbers up to {n}:")
print(*primes)
Command Prompt screenshot of the Python program to print prime numbers from 1 to n: typing 50 prints the 15 primes up to 50
Running the program and typing 50 at the prompt.

Entering 20 gives the prime numbers less than or equal to 20:

Print prime numbers up to: 20
There are 8 prime numbers up to 20:
2 3 5 7 11 13 17 19

Print the first N prime numbers

Here you don’t know in advance how far to count, so loop until the list is long enough:

import math

def is_prime(n):
    """Return True if n is a prime number."""
    if n < 2:
        return False
    for divisor in range(2, math.isqrt(n) + 1):   # only up to the square root
        if n % divisor == 0:
            return False
    return True


def first_n_primes(count):
    primes = []
    num = 2
    while len(primes) < count:      # keep going until we have enough
        if is_prime(num):
            primes.append(num)
        num += 1
    return primes

print(first_n_primes(10))
print(first_n_primes(20))

Output:

[2, 3, 5, 7, 11, 13, 17, 19, 23, 29]
[2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47, 53, 59, 61, 67, 71]
Command Prompt screenshot of a Python program that prints the first 10 and first 20 prime numbers with a while loop
The first 10 and first 20 primes, printed by the program above.

The same with a for loop, printing the first 10 prime numbers. itertools.count(2) counts 2, 3, 4… forever, and break stops it after 10 primes:

# First 10 prime numbers with a for loop (itertools.count never stops by itself)
from itertools import count

found = 0
for num in count(2):
    if all(num % d for d in range(2, int(num ** 0.5) + 1)):
        print(num, end=" ")
        found += 1
        if found == 10:
            break

Output:

2 3 5 7 11 13 17 19 23 29

Prime numbers in a range (interval)

import math

def is_prime(n):
    """Return True if n is a prime number."""
    if n < 2:
        return False
    for divisor in range(2, math.isqrt(n) + 1):   # only up to the square root
        if n % divisor == 0:
            return False
    return True


def primes_between(low, high):
    """Prime numbers in the interval low..high (both included)."""
    return [n for n in range(max(low, 2), high + 1) if is_prime(n)]

print(primes_between(10, 50))
print(primes_between(1, 20))      # prime numbers less than or equal to 20
print(primes_between(90, 96))     # no primes here

Output:

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

More examples: find prime numbers in a range using Python.

One-line prime number program

primes = [n for n in range(2, 101) if all(n % d != 0 for d in range(2, int(n ** 0.5) + 1))]
print(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]

all() is True when no divisor from 2 to √n divides n; for 2 and 3 the range is empty, so all() returns True and they count as prime.

A one-liner that gives the wrong answer

This version turns up in search queries and forums. Its divisor range starts at 3, so 2 is never tested as a divisor and 4 slips through as a “prime” (other even numbers happen to be caught by another divisor):

# A one-liner that is often copied - but it is wrong
primes = [x for x in range(2, 100) if all(x % y != 0 for y in range(3, x))]
print(primes[:12])
print("Contains 4?", 4 in primes, "| Contains 8?", 8 in primes)

Output:

[2, 3, 4, 5, 7, 11, 13, 17, 19, 23, 29, 31]
Contains 4? True | Contains 8? False

Fix: start the inner range at 2 (and stop at the square root), as in the working one-liner above.

Fastest way: the Sieve of Eratosthenes

Instead of testing each number, the sieve starts with every number marked as prime and crosses out the multiples of 2, 3, 5, 7… What’s left is prime. It’s the best choice when you need all primes up to a large limit:

def sieve(limit):
    """Sieve of Eratosthenes: all primes up to limit."""
    if limit < 2:
        return []
    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):   # cross out multiples of n
                is_prime[multiple] = False
    return [n for n, prime in enumerate(is_prime) if prime]

print(sieve(100))
print(len(sieve(1_000_000)), "primes below one million")

Output:

[2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47, 53, 59, 61, 67, 71,