> For the complete documentation index, see [llms.txt](https://kallyasmedia.gitbook.io/cit-python-cohort-three/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://kallyasmedia.gitbook.io/cit-python-cohort-three/week3/python_recursion.md).

# Functions / Python Recursion

Learn how recursion works and how to write a safe recursive function.

Recursion is when a function calls itself. Every recursive function needs a **base case** to stop.

## Example: Factorial

```python
def factorial(n: int) -> int:
    if n == 1:
        return 1
    return n * factorial(n - 1)

print(factorial(3))  # 6
```

## Base Case vs Recursive Case

```python
def countdown(n: int) -> None:
    if n == 0:        # base case
        print("Done")
        return
    print(n)
    countdown(n - 1)  # recursive case
```

## Common Pitfalls

* Missing base case (infinite recursion).
* Very deep recursion causing `RecursionError`.

[Previous](/cit-python-cohort-three/week3/lambda_function.md)
