+ 2
Factorial in Python
I am trying to define a function that returns factorial of an integer. This program is working perfectly fine, but I have one confusion, the answer should be 20 rather than 120. Because this line of code return x * factorial(x - 1) shows multiply x with x-1. If I enter x = 5 then x-1 would be 4, so the answer should be 20 not 120. Why this line of code is multiplying x with x-1 till x becomes 0. there isn't any loop running. here are my codes def factorial(x): if x == 0: return 1 else: return x * factorial(x - 1) print(factorial(5))
4 ответов
+ 4
Mr. Faisal, How the number is keep decreasing till 0 even there isn't any loop running? It should only be decreased till one number according to code.
+ 2
There may not be an explicit statement being called to create a loop (ie. while, for, etc.), calling the function while x does not equal 0 will technically create its own loop that will repeat itself until x equals 0.
Hope this helped!
+ 1
Well, not exactly. What you're doing is calling the function within that same function with the variable x being decreased by 1. This goes on until it reaches 0, multiplying itself by the previous number after every iteration.
+ 1
Lazy people like me will use imports
https://code.sololearn.com/cu00VM8khFtr/?ref=app