Recursive Sum 1 to N
Beginner · Write the code · from Python Recursion: How It Works, When to Use It, and Examples
From the lesson: Python Recursion: How It Works, When to Use It, and Examples
Imagine a set of Russian nesting dolls. You open the biggest one and find a smaller one inside. Open that, and there's an even smaller one. You keep opening until you reach the tiniest doll that doesn't open - that's the end.
Read the lessonWrite a recursive function called sum_to that takes a positive integer n and returns the sum of all numbers from 1 to n.
For example: sum_to(5) should return 1 + 2 + 3 + 4 + 5 = 15.
Base case: sum_to(1) returns 1.
Print the results of sum_to(5) and sum_to(10) on separate lines.
def sum_to(n):
# Your code here
pass
print(sum_to(5))
print(sum_to(10))
More Recursion exercises
- Predict Recursive OutputBeginner
- Fix the Broken Power FunctionIntermediate
- Recursive FibonacciIntermediate
- Reverse a String RecursivelyIntermediate
- Count Digits RecursivelyAdvanced
All Python exercises · 50 practice problems · Functions quiz