Factorial() - how it works if not imported from math module


#1

Hi Collegues,
i have figured out code presented below.
I don`t understand why factorial() method(?) works as to use factorial function would need to use it from math module - math.factorial()...

Would you please help me tu understand step by step ?

def factorial(x):
    if x == 0:
        return 1
    elif x > 0:
        return x * factorial(x-1)
    else:
        return False


print factorial(4)

#2

Hi @marinero2015 ,

This line, inside the function definition, implements the recursive case, in which the function calls itself ...

return x * factorial(x-1)

Provided that a function is defined by the time a call of that function is executed, that call is permissible.

When the Python interpreter first encounters that recursive line of code, the function is still only partially defined. However, that is fine, because the recursive call does not execute until the function definition has been completely processed by the Python interpreter, and you invoke the function by calling it from the outside.

Once the definition is complete, you finally cause the function to execute with this line, and all goes well ...

print factorial(4)

In summary, the factorial function is allowed to call itself because by the time the call is actually executed, the factorial function definition has been completed, and there is no need to use the version from the math module.


#3

This function just like trying to materialise or shedding some light on how the factorial method looks from the backend.:slight_smile:


#4

This topic was automatically closed 7 days after the last reply. New replies are no longer allowed.