 # Output Not Understood

The code and the output are given below. Please help me understanding the output. As my doubt is if n variable in the code has reached the value ‘zero’ then how come the while loop is still running as the output shows? Please consider the indentations correct…
CODE:
def fac_recursive(n,fac=1):
while n>0:
fac=fac*n
n-=1
print(n, fac)
fac_recursive(n,fac)
return(fac)
print(fac_recursive(3))

OUTPUT:
2 3
1 6
0 6
0 6
1 6
0 6
0 6
6

You don’t need to loop over, as the program is already calculating the factorial via recursion.
Change while with if.

``````def fac_recursive(n,fac=1):
if n>0:
fac=fac*n
n-=1
print(n, fac)
fac_recursive(n,fac)
return(fac)
``````
1 Like

Thanks!!! Understood the problem of looping.
But here now the value of ‘fac’ coming at output in the last statement is again wrong… It should have been 6 rather than 3

Yes, i thought it was just for printing out fac values over steps… that’s why just made a correction.

Can you please help me with that …!!! Why the output for the value of fac variable is coming to be 3 rather 6.

I think the answer lies in the fact that the value of fac variable that was assigned in the first instance of func_recursive which is 3 is the one which is being finally returned because we are not storing/assigning the value of fac returned from 2nd and 3rd instance of the recursive function. Instead we should update the value of fac every time with the returned value of fac_recursive function. Therefore the code would become as follows:-

def fac_recursive(n,fac=1):
if n>0:
fac=n*fac_recursive(n-1)
return(fac)

1 Like