In Python language, functions can call other functions. When a function calls itself, we call it recursion. Recursion is not necessary for programing, because theoratically anything solved with recursion can be solved with loops, but recursion shows a clearer logic tan loops do.
Here is an example of recursion. Let's calculate factorial of a number. 'n! = 1 * 2 * 3 * ... * n'. If we use 'fact(n)' to represent this function, we can see that 'fact(n) = n! = 1 * 2 * 3 * ... * (n-1) * n = (n-1)! * n = fact(n-1) * n'. 'fact(n)' can be expressed as 'n * fact(n-1)'. It only needs special care when n = 1. So we can write a function like this:
def fact(n):
if n==1:
return 1
return n * fact(n - 1)
This is a recursive function. In the function bod, we can see that the function calls it self. We can try it with the following examples:
>>> fact(1)
1
>>> fact(5)
120
>>> fact(100)
93326215443944152681699238856266700490715968264381621468592963895217599993229915608941463976156518286253697920827223758251185210916864000000000000000000000000
Let's trace fact(5), then we can see:
===> fact(5)
===> 5 * fact(4)
===> 5 * (4 * fact(3))
===> 5 * (4 * (3 * fact(2)))
===> 5 * (4 * (3 * (2 * fact(1))))
===> 5 * (4 * (3 * (2 * 1)))
===> 5 * (4 * (3 * 2))
===> 5 * (4 * 6)
===> 5 * 24
===> 120
However, using recursion needs to pay attention to stack overflow. In computer, function calls are achieved by a data structure called stack. Every function being called will cause the size of call stack to plus 1, and each return will reduce that by 1.
Since size of call stack is not infinite, so that when there are too many function calls in a recursion, a stack overflow will occur. For instance, if we try fact(1000), we can see the following error:
Traceback (most recent call last):
File "/Applications/Wing101.app/Contents/Resources/src/debug/tserver/_sandbox.py", line 1, in <module>
# Used internally for debug sandbox under external interpreter
...
File "/Applications/Wing101.app/Contents/Resources/src/debug/tserver/_sandbox.py", line 2, in fact
if __name__ == '__main__':
builtins.RuntimeError: maximum recursion depth exceeded in comparison
Last but not the least, when you write a recursion, you must take all possibilities into account. That's because when when no conditions are satisfied, the function will run the code under the ifs, elifs and else and nothing will be returned. When nothing is returned, Python returns None. It will cause an error like the following:
Traceback (most recent call last):
File "<...>", line 1, in ?
File "<...>", line 2, in ...
File "<...>", line 2, in ...
...
File "<...>", line 2, in ...
TypeError: unsupported operand type(s) for +: 'int' and 'NoneType'