Recursive functions
When a function calls itself, this is known as a recursive function. This is similar to for
loops; however, recursive functions allow you to write more elegant and terse functions than can be achieved with a loop.
You may imagine that a function that calls itself recursively might end up in an infinite loop; you can write a recursive function that will keep running indefinitely, as shown here:
def print_the_next_number(start):
print(start + 1)
return print_the_next_number(start + 1)
print_the_next_number(5)
The output starts as follows:
6
7
8
9
10
11
Note
This output is truncated.
If you run this code in a Python shell, it will continue printing integers until you interrupt the interpreter (Ctrl + C); in a Jupyter Notebook, you can interrupt or restart the kernel under the Kernel tab. Take a look at the preceding code and ensure you understand why...