Sum of Primes in Range
Add all primes in an inclusive interval. Students reuse trial division and accumulate matching values rather than counting or printing each match separately.
1# Helper function2def is_prime(n):3 if n < 2:4 return False5 for i in range(2, int(n ** 0.5) + 1):6 if n % i == 0:7 return False8 return True910# Take range11a = int(input("Enter start: "))12b = int(input("Enter end: "))1314# Sum primes15total = 016for num in range(a, b + 1):17 if is_prime(num):18 total += num1920print(f"Sum of primes: {total}")
Output
Enter start: 1 Enter end: 10 Sum of primes: 17
In this one
- Filter before adding
- Search both interval endpoints
- Keep an empty sum
How it works
- 1
Initialize total zero.
- 2
Visit a through b and test each value for primality.
- 3
Add prime values and print the completed sum.
Edge cases
What if start exceeds end?
What if start exceeds end?
The loop is empty and total remains zero.
Are endpoints included?
Are endpoints included?
Yes. Both can contribute if prime.
What's going on
The outer loop visits a through b. is_prime classifies each candidate, and a successful candidate is added to total.
For two through five, the result is ten from two, three, and five. Negative candidates and one are rejected by the helper's first test. A reversed interval gives an empty range and zero, not an automatically reordered search.
What if start exceeds end? The loop is empty and total remains zero.
Are endpoints included? Yes. Both can contribute if prime.
Quiz
Tap an option. The answer stays hidden until you pick.
Question 1
What is added after a match?
Pick an answer to check it.
Question 2
What if start exceeds end?
Pick an answer to check it.
Questions people ask
What if start exceeds end?
The loop is empty and total remains zero.
Are endpoints included?
Yes. Both can contribute if prime.
What is added after a match?
The prime value.
๐Related Content
- ๐
Phase 6 - Learn Concepts
Review Phase 6 concepts and explanations
- ๐
Phase 6 - Quiz
Test your Phase 6 understanding with quiz questions
- ๐ป
Phase 6 - All Practice Problems
Explore all practice problems for Phase 6
- ๐
Master Your Logic Building - Complete Course
Browse all phases and tutorials
- ๐ง
Logic Building Overview
Learn about the complete logic building curriculum