In Python, recursion is a function calling itself using the iterative approach to do complex tasks. Here is an example to find factorial of a number using recursion:
def factorial(x):
"""This is a recursive function
to find the factorial of an integer"""
if x == 1:
return 1
else:
return (x * factorial(x-1))
Here, factorial() is a recursion function and it is calling itself by decreasing the number by 1 in each iteration. This factorial() function call itself until the x value equals to 1.
Here is how the recursion call can be explained:
factorial(4) # 1st recursive call with 4
4 * factorial(3) # 2nd recursive call with 3
4 * 3 * factorial(2) # 3rd recursive call with 2
4 * 3 * 2 * factorial(1) # 4th recursive call with 1
4 * 3 * 2 * 1 # return from 4th call as number=1
4 * 3 * 2 # return from 3rd recursive call
4 * 6 # return from 2nd recursive call
24 # return from 1st recursive call
If you want to learn Python, you can check out this Python course by Intellipaat that provides Instructor-led training, hands-on experience, and certification also.
You can watch this video on Python for beginners to know about recursion.