Recursion can sound complicated at first, but it is simply a way for a function to call itself. Instead of repeating code or writing long loops, you can let the function handle the repetition by calling itself again with slightly different input. This can be useful for tasks that involve breaking a problem into smaller pieces.
How recursion works
A recursive function is just like any other function, but inside it you write a call to the same function. Each call works on a smaller or simpler version of the original problem until you reach a point where the function stops calling itself. That stopping point is called the base case.
def countdown(n):
if n == 0:
print("Done!")
else:
print(n)
countdown(n - 1)
countdown(5)
Here, the function keeps calling itself with a smaller number until it reaches 0. The base case is when n == 0. Without a base case, the function would call itself forever.
Why recursion is useful
Recursion can make code shorter and easier to read, especially for problems that naturally break into smaller pieces. Examples include exploring folders inside folders, solving puzzles like the Towers of Hanoi, or working with tree-like data. Although loops can solve the same problems, recursion can sometimes feel more natural.
Example with strings
We can also use recursion to reverse a string such as “LiddleBit”.
def reverse_string(text):
if text == "":
return text
else:
return reverse_string(text[1:]) + text[0]
print(reverse_string("LiddleBit"))
This works by peeling off the first letter and adding it to the reversed version of the rest of the string.
Things to try yourself
- Write a function that prints the numbers from 1 to 10 using recursion.
- Write a function that adds up the numbers from 1 to
nusing recursion. - Modify the string reversal function so that it checks if the string is a palindrome (the same forwards and backwards).
- Experiment with what happens if you remove the base case. What error do you get?
Recursion takes practice, but once you understand the idea of a function calling itself and always having a base case, it becomes a powerful tool in your Python toolkit.




