Python Practice › Loop Programs › Program 32
Primes from 1 to n
Write a Python program to print all prime numbers from 1 to n.
Input
n = 50
Output
[2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47]
Approach
- Test each number with a helper function.
Solution
def is_prime(n): if n < 2: return False for d in range(2, int(n ** 0.5) + 1): if n % d == 0: return False return True print([n for n in range(1, 51) if is_prime(n)])Output
[2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47]
Line by line
Line 9
The comprehension keeps the numbers that pass the test.
Learn the concept
New to this topic? Read the lesson, then come back.