Recursion
Recursion refers to recursive functions; functions which call themselves. Recursion can be used in a similar manner to looping. However, in Python, recursion is generally less useful than loops.
To start, Python has a built-in recursion depth that prevents recursion from going to far— this is to prevent run-away recursion from resultin gin a crash, memory overuse, or both.
def infinite(num):
print(num, end='\r')
infinite(num+1)
If the function calls itself too many times, it will arbitrarily be terminated, and an exception will be thrown.
try:
infinite(5)
except RecursionError:
print("Maximum recursion depth exceeded.")
That being said, there are some cases where recursion makes more sense than alternative methods of performing certain tasks.
def factorial(n):
if n > 1:
return n * factorial(n-1)
else:
return 1
print(factorial(5))
120
A looping factorial function, by comparison, might look like this:
def factorial(n):
product = 1
for i in range(1, n+1):
product *= i
return product
print(factorial(5))
120
In practice, recursion usually turns out to be completely optional. There are almost always different, if not better ways to do things.