Keyboard Shortcuts N Next post
P Previous post
S Save / unsave
R Read aloud
T Toggle theme
/ Focus search
Esc Close panels
🔥
Ready to read...
Functions Module 4 - Functions Python Python Basics Python Programming: From Zero to Real-World Applications

Recursion in Python - Functions That Call Themselves

Reviewed & accurate
AI Summary

What You Will Learn

Intermediate

  • What recursion is and how it works
  • Base case and recursive case
  • Factorial and Fibonacci examples
Terminalpython
# Factorial: n! = n * (n-1)!
def factorial(n):
    # Base case: stop condition
    if n <= 1:
        return 1
    # Recursive case: call itself
    return n * factorial(n - 1)

print(factorial(5))   # 120 (5 * 4 * 3 * 2 * 1)
print(factorial(0))   # 1

Fibonacci Sequence

Terminalpython
def fibonacci(n):
    if n <= 1:
        return n
    return fibonacci(n - 1) + fibonacci(n - 2)

for i in range(10):
    print(fibonacci(i), end=" ")
# 0 1 1 2 3 5 8 13 21 34
Every recursion needs a base case
Without a base case (stop condition), recursion runs forever and causes RecursionError. Always define when to stop.
Python recursion limit
Python has a default recursion limit of 1000. For deep recursion, use sys.setrecursionlimit() or rewrite as a loop.

Practical Exercise

Write factorial(5) - trace the calls
Write fibonacci(10) - print first 10 numbers
Add a base case to prevent infinite recursion
Try factorial(1000) - see the RecursionError

Key Takeaways

  • Recursion = function calls itself.
  • MUST have a base case (stop condition).
  • Factorial: n! = n * (n-1)!
  • Fibonacci: fib(n) = fib(n-1) + fib(n-2).
  • Python limit: 1000 recursive calls. Use loops for deep recursion.
Previously: Lesson 28 covered lambda.
Today: You learned: Functions that call themselves.
Next: Module 4 complete! Module 5 begins with lesson 30.
Test Your Knowledge
How did you find this?

Comments

Join the discussion! Sign in with your Google or Blogger account, or comment as Anonymous - no account needed. For quick questions, also reach me on Telegram @cytestch.

Comments