Recursion, explained simply
Recursion is when a function calls itself. It sounds like a loop that never ends, but done well, each call works on a slightly smaller problem.
Every recursive function needs a base case: a simple situation where it stops calling itself and just gives an answer. Without one, Python eventually stops with a RecursionError.
Think of walking down a staircase: to get down 5 steps, take one step, then get down 4 steps. When there are 0 steps left, you are done.
Example: Walk down the stairs
def walk_down(steps):
if steps == 0:
print("At the bottom!")
return
print("Step", steps)
walk_down(steps - 1)
walk_down(3)Output
Step 3
Step 2
Step 1
At the bottom!Try this
- Write a recursive function that adds up all the numbers from 1 to n.
- Move the print line after the recursive call and predict the new order.
- Remove the base case and read the error Python gives.
