Understanding Recursive Functions with Python
Introduction
When we think about repeating a task, we usually think about the for
and while
loops. These constructs allow us to perform iteration over a list, collection, etc.
However, there’s another form of repeating a task, in a slightly different manner. By calling a function within itself, to solve a smaller instance of the same problem, we’re performing recursion.
These functions call themselves until the problem is solved, practically dividing the initial problem to a lot of smaller instances of itself – like for an example, taking small bites of a larger piece of food.
The end goal is to eat the entire plate of hot pockets, you do this by taking a bite over and over. Each bite is a recursive action, after which you undertake the same action the next time. You do this for every bite, evaluating that you should take another one to reach the goal, until there are no hot pockets left on your plate.
What is Recursion?
As stated in the introduction, recursion involves a process calling itself in the definition. A recursive function generally has two components:
- The base case which is a condition that determines