Nearby lessons

66 of 108

Python - Recursive Functions

What Is Recursion?

A recursive function is a function that calls itself.

Recursion is useful for problems that can be broken into smaller versions of the same problem.

Factorial Example

def factorial(n):
    if n == 0:
        return 1
    return n * factorial(n - 1)

Why Use Recursion?

  • Shorter code
  • Cleaner logic for some problems
  • Useful for factorial, tree traversal, and divide-and-conquer problems

Important Rule

Every recursive function must have a base case, or it may keep calling itself forever.

Summary

Term Meaning
Recursive functionFunction that calls itself
Base caseCondition that stops recursion
Recursive caseCalls the same function again

🧠 Test Your Knowledge

3 Questions

Progress: 0 / 3
Keep Going!Python - Lambda Functions