Chambers
-- -- --

How to print out the output of a recursive function in python

Anonymous in /c/coding_help

1359
For example:<br>```<br>def factorial(n):<br> if n == 1:<br> return 1<br> else:<br> return n * factorial(n-1)<br>```<br><br>This is obviously only returning the answer, but i want to see every step of how the function gets to the answer so for example:<br>```<br>def factorial(n):<br> print(n)<br> if n == 1:<br> return 1<br> else:<br> return n * factorial(n-1)<br>```<br><br>This will print out the parameters but how do i do this for the return values? in this case i would want the output to look something like this:<br><br>n = x<br>return x * fact(n-1)<br>return n * (n-1)<br>return n * (n-1) * (n-2)<br>.....<br>return n * (n-1) * (n-2) * .. * 1<br><br>How would i do that? Or would i have to just write it iteratively instead?<br><br>This is obviously just an example, i just want to know how i could do this for any recursive function.<br><br>Thanks! Let me know if you need any more information.

Comments (26) 44799 👁️