Python Recursion
Recursion is part of objective 4.1 and is examined narrowly: given a recursive function, what does it return, and what happens if the base case is missing. Both are answerable by tracing, and this guide traces one on the machine rather than in prose. The cost is worth seeing too - naive fib(20) makes 21891 calls, which is a number rather than an opinion.
Functions and Scope Guide 21 of 26 Intermediate
- OSUbuntu 26.04 LTS
- Python3.14.4
- pip25.1.1
- TimeAbout 15 min
The default recursion limit is 1000 and has been for a long time. Python does not optimise tail calls, and there is no plan to; a deep recursion will always raise rather than loop.
| Server Name | IP Address | OS | Roles | CPU | RAM | HDD |
|---|---|---|---|---|---|---|
| RUNNER01 | 192.168.0.27 | Ubuntu 26.04 LTS | Python 3.14.4 - the only machine this path needs | 2 Core | 4 GB | 50 GB |
This guide includes
Use this when you need to trace a recursive function rather than write one. This matters because that is exactly how the exam asks it - given a definition and a call, say what comes back.
- writing factorial, and naming the two parts every recursion has
- watching the call stack, with a depth parameter
- seeing what the naive recursive Fibonacci costs
- running a recursion with no reachable base case
- writing the same job without recursion
Before you start
- guide 18 -
returnends a call. - guide 20 - each call has its own locals, which is what makes recursion work.
-
Factorial, and the two parts every recursion has
-
What the call stack actually does
-
Fibonacci, and what it costs
-
A recursion with no base case
-
The same job without recursion
-
What the exam does with recursion