Search code examples
pythonrecursionfactorial

Cannot understand how is a function looped without loop function in python while finding factorial number


def factorial(num):
    if num == 0:
        return 1
    return num * factorial(num-1)

print('Enter an integer')
num = int(input())
print(factorial(num)

If I input number 4, output is 24.

Inside the above code block, I cannot understand line 4.

Though there isn't any loop, how does that function multiply all the numbers under a given number and returns the value that we expected?


Solution

  • Execute it in your head. For example - what is factorial(2)? 2 is not 0, so it is 2 * factorial(1). Now what is factorial(1)? 1 is still not 0, so it is 1 * factorial(0). What is factorial(0)? Now 0 is 0, so we know it's 1. Going backwards now to plug in our missing pieces: if factorial(0) is 1, then factorial(1) is 1 * 1, then factorial(2) is 2 * 1 * 1.

    With recursion, there is a base (or terminating) case which is known, and all the other cases are reduction to simpler problems that approach the base case. You know factorial(24) only if you know factorial(23), you know factorial(23) only by knowing factorial(22)... but you know factorial(0) unconditionally. If there is no terminating case, then you get the equivalent of an infinite loop - an infinite recursion.

    In order to understand recursion, you should first understand recursion.