Python Practice › Function Programs › Program 26
Primes from 1 to 100
Write a Python function that returns the prime numbers from 1 to 100.
Output
25 [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]
Approach
- Reuse a prime test inside a comprehension.
Solution
def is_prime(n): return n > 1 and all(n % d for d in range(2, int(n ** 0.5) + 1)) def primes_upto(limit): return [n for n in range(1, limit + 1) if is_prime(n)] primes = primes_upto(100)print(len(primes), primes)Output
25 [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]
Learn the concept
New to this topic? Read the lesson, then come back.