Editor

Python Program to Print All Prime Numbers in a Range

Beginner · Numbers

A prime number is a whole number greater than 1 whose only divisors are 1 and itself, like 2, 3, 5 and 7. This program prints every prime number between two limits by checking each number in the range for a divisor.

Program

primes_in_range.py
start = 10 # or: start = int(input("Enter the start: "))
end = 50 # or: end = int(input("Enter the end: "))
primes = []
for num in range(start, end + 1):
if num < 2:
continue # 0 and 1 are not prime
is_prime = True
for i in range(2, int(num ** 0.5) + 1):
if num % i == 0:
is_prime = False
break
if is_prime:
primes.append(num)
print(f"Prime numbers between {start} and {end}:")
print(primes)
print("How many:", len(primes))
Output
Prime numbers between 10 and 50:
[11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47]
How many: 11

How it works

  1. The outer loop visits every number from start to end, both included.
  2. continue skips 0 and 1 straight away, since they are not prime.
  3. The inner loop looks for a divisor from 2 up to the square root of num; the first one it finds sets is_prime to False and break stops the search.
  4. Numbers with no divisor are added to the primes list, which is printed with its length at the end.

Other ways to write it

Sieve of Eratosthenes

Sieve of Eratosthenes
limit = 50
is_prime = [True] * (limit + 1)
is_prime[0] = is_prime[1] = False
for i in range(2, int(limit ** 0.5) + 1):
if is_prime[i]:
# Cross out every multiple of i, starting at i * i
for multiple in range(i * i, limit + 1, i):
is_prime[multiple] = False
primes = [n for n in range(limit + 1) if is_prime[n]]
print(f"Primes up to {limit}: {primes}")
Output
Primes up to 50: [2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47]

The sieve crosses out the multiples of each prime instead of testing every number for divisors, which is much faster for big limits like a million.

Using for-else

Using for-else
print("Primes between 2 and 30:")
for num in range(2, 31):
for i in range(2, num):
if num % i == 0:
break
else:
print(num, end=" ")
print()
Output
Primes between 2 and 30:
2 3 5 7 11 13 17 19 23 29

The else of a for loop runs only when the loop ends without a break, so it fires exactly for the numbers that had no divisor.

Try it yourself

Change the range to 1 to 100 and check that the program finds 25 primes.

Edit the program above and press Run, or open it in the full editor to save it and share it. To watch it run line by line, open it in the visualizer.

All Python programs · CBSE class 12 practical file · Python exercises