Sum of Primes in Range

Calculate sum of all primes in range.

IntermediatePhase 6 - Category 3: Loop & Conditional MixExample 2 of 10
sum-of-primes-in-range.py
1# Helper function
2def is_prime(n):
3 if n < 2:
4 return False
5 for i in range(2, int(n ** 0.5) + 1):
6 if n % i == 0:
7 return False
8 return True
9
10# Take range
11a = int(input("Enter start: "))
12b = int(input("Enter end: "))
13
14# Sum primes
15total = 0
16for num in range(a, b + 1):
17 if is_prime(num):
18 total += num
19
20print(f"Sum of primes: {total}")

Output

Enter start: 1
Enter end: 10
Sum of primes: 17

What's going on

Find primes and accumulate sum.

Key Concepts:

Check each number for prime
Add to sum if prime
Return total sum