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
Prime numbers between 10 and 50: [11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47] How many: 11
How it works
- The outer loop visits every number from
starttoend, both included. continueskips 0 and 1 straight away, since they are not prime.- The inner loop looks for a divisor from 2 up to the square root of
num; the first one it finds setsis_primetoFalseandbreakstops the search. - Numbers with no divisor are added to the
primeslist, which is printed with its length at the end.
Other ways to write it
Sieve of Eratosthenes
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
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.
Related programs
All Python programs · CBSE class 12 practical file · Python exercises