Could someone explain the output step by step for the factorial code ? | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
+ 1

Could someone explain the output step by step for the factorial code ?

def factorial(n): if n == 0: return 1 else: recurse = factorial(n-1) result = n * recurse return result >>>factorial(5) 120

22nd Feb 2020, 6:59 PM
Milad Zarour
Milad Zarour - avatar
3 Answers
+ 2
(...continued, sorry ran out of character room for the first part lol) Here, n=5 and recurse=24 because 24 is the return value of the previous iteration. 24*5=120, and 120 is returned as the final result which is then output. 5 factorial, denoted as 5! = 5*4*3*2*1 is what this recusive function is used to calculate and would work with other numbers as well I hope this helped a little, recursion can be difficult to wrap your head around and someone else may have a better way of explaining it. It can be thought of as for each time the function is called a new “layer” or “level” is created until a value is returned, then you move back up through the levels until all operations are complete and a final value is returned
22nd Feb 2020, 8:11 PM
Kylie
Kylie - avatar
+ 2
You can sort of think of recursion as “layers” of a function calling itself until it can escape To start n=5 so the first condition will be false, meaning in the else statement the recurse variable will be set to the return value of factorial(n-1) Essentially, factorial(4) is now being called, and in the next iteration n=4. n!=0 so factorial(n-1) will be called once again. factorial(3) will do the same, continuing until n=0 where the if statment will be true. In this case, the function call for the “layer” above will return 1 as the value. recurse will be set to equal 1 in the iteration where n=1. result = 1*1 = 1, 1 is returned and we go back to the “layer” above. 1 is returned and recurse is set to 1. In this iteration n=2 so result will be 2*1 which means 2 will be returned. To the n=3 iteration, recurse will be 2 and result=3*2=6. 6 will be returned. In the next layer, n=4 and recurse is 6. 4*6=24, 24 is returned. Finally, we’re back to the first layer where we originally called factorial(5)...
22nd Feb 2020, 8:05 PM
Kylie
Kylie - avatar
+ 1
Thx a lot, it is sooo complicated for a beginner
22nd Feb 2020, 10:15 PM
Milad Zarour
Milad Zarour - avatar