Sum of Primes in Range

Calculate sum of all primes in range.

Logic BuildingIntermediate
Logic Building
# Helper function
def is_prime(n):
    if n < 2:
        return False
    for i in range(2, int(n ** 0.5) + 1):
        if n % i == 0:
            return False
    return True

# Take range
a = int(input("Enter start: "))
b = int(input("Enter end: "))

# Sum primes
total = 0
for num in range(a, b + 1):
    if is_prime(num):
        total += num

print(f"Sum of primes: {total}")

Output

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

Find primes and accumulate sum.

Key Concepts:

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