To understand recursion, one must first understand recursion. Recursion in programming is an opportunity to define a function using its definition.
Mathematics defines it this way, which is why most programming languages adopt this approach. Python is no exception here: usually, you can only use definitions given earlier in the function body. But there is one exception, a function can call itself in its body. It looks like this:
def factorial(n):
if n <= 0:
return 1
return n * factorial(n - 1)
https://replit.com/@hexlet/Python-functions-recursion-factorial#main.py
This function calculates the factorial of the number n
by multiplying the number by the factorial of the number n - 1
.
Recursions as termination conditions
The example demonstrates a condition that terminates the recursion. The first call to this function will cause the program to loop if you remove it in this function that checks that the argument is not negative. The function will continue to call itself again and again.
There is almost always a similar condition in the definitions of recursive functions. It allows the calculation to go along one of two branches:
- Either recursive, where the function calls itself sometimes multiple times
- Or terminal, which will terminate the function and return the result
There is a rule — some of the arguments of a recursive function must always decrease.
Decreasing can mean lowering the counter, dropping the head of the list when moving to its tail, or the function calling itself part of the original structure when processing tree-like data structures.
Unfortunately, it is generally only possible to tell that a program will not loop by staring at it and using tests. It is essential to check that the recursion termination condition gets triggered.
Stack overflows
In most programs written in languages that support function calls, this very call goes as follows: