Python Practice › Loop Programs › Program 33
Sum of primes from 1 to n
Write a Python program to find the sum of all prime numbers from 1 to n.
Input
n = 100
Output
Sum of primes up to 100: 1060
Approach
- Reuse a prime test and add the primes.
Solution
def is_prime(n): return n > 1 and all(n % d for d in range(2, int(n ** 0.5) + 1)) total = 0for n in range(1, 101): if is_prime(n): total += nprint("Sum of primes up to 100:", total)Output
Sum of primes up to 100: 1060
Line by line
Line 2
all(n % d ...) is True when every remainder is non-zero, meaning no divisor exists.
Learn the concept
New to this topic? Read the lesson, then come back.