Notice: This page requires JavaScript to function properly.
Please enable JavaScript in your browser settings or update your browser.
Learn Recursion | Recursion and Lambda Functions
Python Functions Tutorial
Section 5. Chapter 1
single

single

bookRecursion

Swipe to show menu

Note
Definition

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

123456
def 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)
copy

Go step by step to understand how this works:

  1. times = 3 → condition is true, print message, call print_message(message, 2);
  2. times = 2 → condition is true, print message, call print_message(message, 1);
  3. times = 1 → condition is true, print message, call print_message(message, 0);
  4. 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.

Note
Note

Every recursive function must have a base case. Without it, the function will call itself forever and cause a RecursionError.

Task

Swipe to start coding

Implement a recursive function list_sum that calculates the sum of all elements in a list.

  1. If the list numbers is empty, return 0 — this is the base case;
  2. Otherwise, return the first element added to the result of a recursive call with the rest of the list.

Solution

Switch to desktopSwitch to desktop for real-world practiceContinue from where you are using one of the options below
Everything was clear?

How can we improve it?

Thanks for your feedback!

Section 5. Chapter 1
single

single

Ask AI

expand

Ask AI

ChatGPT

Ask anything or try one of the suggested questions to begin our chat

some-alt