Sololearn: Learn to Code
New course! Every coder should learn Generative AI!
Try a free lesson
+ 3
Well, the else statement is where the actual factorial happens. "if x == 1" is the break condition. For every number x that is not 1, it will return x * factorial(x - 1). That's 2 * factorial(1) for 2; 3 * factorial(2) for 3 etc. So factorial(3) is 3 * factorial(2 * factorial(1)), which is 3 * (2 * (1)) = 6.
17th Dec 2018, 9:54 PM
Anna
Anna - avatar
+ 2
The function keeps calling itself with the value from before minus 1, until x == 1. Then 1 is returned, and from there the whole stack of function 'windows' gets closed one after another. Imagine you call this function with 2. So the first (and only) inside call will be 2 * factorial(2-1). 1 will be returned, so what's actually written there is 2 * 1. And if you call it with 3, it will be 3*(3-1)* (return chain starts now) 1. (Did that even make sense?)
17th Dec 2018, 10:54 PM
HonFu
HonFu - avatar