Search code examples
pythonrecursionfactorial

I have trouble understanding the return command in recursion


def fac(n):
    if (n < 1):
        return 1
    else:
        n * fac(n-1)
print fac(4)

Why does return command cause the function to go back up and multiply the factorials? I have trouble understanding this.


Solution

  • 1). You need to write a return in your code.

    def fac(n):
    if (n < 1):
        return 1
    else:
        return n * fac(n-1)
    print(fac(4))
    

    2). I am uploading a picture which will help you to understand the concept of recursion. Follow the arrow from start to end in the picture. enter image description here