Opening Hours :7AM to 9PM
In this tutorial, you will learn to create a recursive function (a function that calls itself).
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)) if __name__=="__main__": n = 3 print("The factorial of", n, "is", factorial(n))
factorial(3) # 1st call with 3 3 * factorial(2) # 2nd call with 2 3 * 2 * factorial(1) # 3rd call with 1 3 * 2 * 1 # return from 3rd call as number=1 3 * 2 # return from 2nd call 6 # return from 1st callLet's look at an image that shows a step-by-step process of what is going on:
def recursor(): recursor() recursor()Output Traceback (most recent call last): File "<string>", line 3, in <module> File "<string>", line 2, in a File "<string>", line 2, in a File "<string>", line 2, in a [Previous line repeated 996 more times] RecursionError: maximum recursion depth exceeded