Sum Series with Steps Recursively
Sum a descending stepped series recursively. Students trace a nonpositive stopping condition and see why the step must move the argument toward that condition.
1def sum_series(n, step=1):2 # Base case3 if n <= 0:4 return 056 # Recursive case7 return n + sum_series(n - step, step)89# Test10n = int(input("Enter n: "))11step = int(input("Enter step: "))12result = sum_series(n, step)13print(f"Sum: {result}")
Output
Enter n: 10 Enter step: 2 Sum: 30
In this one
- Subtract a positive step
- Use a nonpositive base case
- Detect missing progress
How it works
- 1
Return zero when n is nonpositive.
- 2
Request the series beginning at n - step.
- 3
Add the current n to the returned total.
Edge cases
What if n is already negative?
What if n is already negative?
The base case returns zero immediately.
What if step is zero?
What if step is zero?
For positive n, calls repeat until RecursionError.
What's going on
The current n is added to a smaller problem with n - step. The base case returns zero when n is nonpositive.
With n equal to seven and step two, terms are seven, five, three, and one. A positive step guarantees progress. A zero step repeats the same argument; a negative step increases it. Both can exhaust Python's call stack instead of finishing.
What if n is already negative? The base case returns zero immediately.
What if step is zero? For positive n, calls repeat until RecursionError.
Quiz
Tap an option. The answer stays hidden until you pick.
Question 1
Which step is valid for progress?
Pick an answer to check it.
Question 2
What if n is already negative?
Pick an answer to check it.
Questions people ask
What if n is already negative?
The base case returns zero immediately.
What if step is zero?
For positive n, calls repeat until RecursionError.
Which step is valid for progress?
A positive step.
๐Related Content
- ๐
Phase 3 - Learn Concepts
Review Phase 3 concepts and explanations
- ๐
Phase 3 - Quiz
Test your Phase 3 understanding with quiz questions
- ๐ป
Phase 3 - All Practice Problems
Explore all practice problems for Phase 3
- ๐
Master Your Logic Building - Complete Course
Browse all phases and tutorials
- ๐ง
Logic Building Overview
Learn about the complete logic building curriculum