single
Recursion
Swipe to show menu
A recursive function is a function that calls itself to solve a problem by breaking it down into smaller, simpler parts.
The key elements of recursion are:
- Base case: the condition that stops the recursion;
- Recursive case: the part where the function calls itself with a simpler input.
Why Use Recursion?
Some problems can be naturally expressed in terms of smaller subproblems. Recursion provides a clean and elegant way to solve these by having a function call itself to handle the simpler cases. It is commonly used in tasks like processing trees, exploring paths, or breaking down structures (e.g., lists, strings).
A Simple Example
123456def print_message(message, times): if times > 0: # Base case: stop when times is 0 print(message) print_message(message, times - 1) # Recursive case print_message("Hello, Recursion!", 3)
Go step by step to understand how this works:
times = 3→ condition is true, print message, callprint_message(message, 2);times = 2→ condition is true, print message, callprint_message(message, 1);times = 1→ condition is true, print message, callprint_message(message, 0);times = 0→ condition is false, recursion stops.
Result: the message is printed three times.
The Call Stack
Each time the function calls itself, it adds a new frame to the call stack — a memory structure that keeps track of active function calls. Once the base case is reached, each previous call completes one by one in reverse order.
Every recursive function must have a base case. Without it, the function will call itself forever and cause a RecursionError.
Swipe to start coding
Implement a recursive function list_sum that calculates the sum of all elements in a list.
- If the list
numbersis empty, return0— this is the base case; - Otherwise, separate the first element from the rest. Return the first element (
numbers[0]) added to the result of callinglist_sum()again with the rest of the list (numbers[1:]).
Solution
Thanks for your feedback!
single
Ask AI
Ask AI
Ask anything or try one of the suggested questions to begin our chat