๐ Python Mistakes Everyone Makes ❌
Day 23: Using Recursion Without a Base Case
Recursion is powerful, but without a base case, it becomes dangerous. A recursive function must always know when to stop.
❌ The Mistake
def countdown(n):print(n)countdown(n - 1)
This function keeps calling itself endlessly.
✅ The Correct Way
def countdown(n):if n == 0: # base casereturnprint(n)countdown(n - 1)
Here, the base case (n == 0) tells Python when to stop making recursive calls.
❌ Why This Fails
-
No condition to stop recursion
-
Function keeps calling itself forever
-
Leads to RecursionError: maximum recursion depth exceeded
-
Can crash your program
๐ง Simple Rule to Remember
✔ Every recursive function must have a base case
✔ The base case defines when recursion ends
✔ No base case → infinite recursion
๐ Pro tip: Always ask yourself, “When does this recursion stop?”


0 Comments:
Post a Comment