Recursive function is a function that calls itself in order to create a loop.
def sum(number):
if number == 0:
return 0
return number + sum(number - 1) # calls itself , which loops
print(sum(5))
15
In the above sum() is a recursive function which calls it self.
When we call the function sum with an integer 5, it recursively calls itself return number + sum(number - 1)
, by decreasing number passed to it by1
There is a condition if number == 0
, which checks the number values each time it is called and returns 0 once it reaches 0.
This condition has to be kept to avoid the number to become negative and to avoid the recursion to go to an infinite loop.
So the recursion function should have an condition to terminate recursion and avoid infinite loop
The above recursion function purpose can also be solved using python loops. Loops are faster than recursion
sum = 0
for i in range(5+1): # range(5+1) -> [0, 1, 2, 3, 4, 5]
sum += i
print(sum)
15