+ 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))

28th Jan 2018, 7:09 PM
Abdul Basit
Abdul Basit - avatar
4 Respuestas
+ 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.
28th Jan 2018, 7:18 PM
Abdul Basit
Abdul Basit - avatar
+ 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!
28th Jan 2018, 7:20 PM
Faisal
Faisal - avatar
+ 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.
28th Jan 2018, 7:15 PM
Faisal
Faisal - avatar
+ 1
Lazy people like me will use imports https://code.sololearn.com/cu00VM8khFtr/?ref=app
1st Jun 2018, 8:16 PM
Shuaib Nuruddin
Shuaib Nuruddin - avatar