What is happening?
This is a recursive function, where the function sum() calls itself.
But it is missing a base case, which is essential in recursion to stop the loop.
Step-by-step execution:
-
sum(2)
→ returns 2 + sum(1) -
sum(1)
→ returns 1 + sum(0) -
sum(0)
→ returns 0 + sum(-1) -
sum(-1)
→ returns -1 + sum(-2) -
... and so on, forever...
It keeps calling itself with smaller and smaller numbers and never stops.
❌ Problem:
There is no base case like:
So Python will eventually stop the program and raise this error:
✅ How to fix it?
Add a base case to stop recursion:
Summary:
| Concept | Explanation |
|---|---|
| Recursion | Function calling itself |
| Base Case | Missing → causes infinite recursion |
| Error Raised | RecursionError |
| Fix | Add if num == 0: return 0 |


0 Comments:
Post a Comment