I have a simple factorial function written in python with a bunch of debug embedded to aid my understanding of what is going on. However, the output has confused me even more. Can anyone help me understand? (BTW, in case there was a print output timing issue, I ran it several times but got exactly the same output.)
recursive_function.py
def recursive(n): if n == 1: return 1 print ('n : {}'.format(n)) print ('recursive return value is: {}'.format(n*recursive(n-1))) return n*recursive(n-1) x = recursive(5) print('***** End result is: {}'.format(x)) (with line numbers)
1 n : 5 2 n : 4 3 n : 3 4 n : 2 5 recursive return value is: 2 6 recursive return value is: 6 7 n : 2 8 recursive return value is: 2 9 recursive return value is: 24 10 n : 3 11 n : 2 12 recursive return value is: 2 13 recursive return value is: 6 14 n : 2 15 recursive return value is: 2 16 recursive return value is: 120 17 n : 4 18 n : 3 19 n : 2 20 recursive return value is: 2 21 recursive return value is: 6 22 n : 2 23 recursive return value is: 2 24 recursive return value is: 24 25 n : 3 26 n : 2 27 recursive return value is: 2 28 recursive return value is: 6 29 n : 2 30 recursive return value is: 2 31 ***** End result is: 120 (cleaner output without line numbers)
n : 5 n : 4 n : 3 n : 2 recursive return value is: 2 recursive return value is: 6 n : 2 recursive return value is: 2 recursive return value is: 24 n : 3 n : 2 recursive return value is: 2 recursive return value is: 6 n : 2 recursive return value is: 2 recursive return value is: 120 n : 4 n : 3 n : 2 recursive return value is: 2 recursive return value is: 6 n : 2 recursive return value is: 2 recursive return value is: 24 n : 3 n : 2 recursive return value is: 2 recursive return value is: 6 n : 2 recursive return value is: 2 ***** End result is: 120 
n*recursive(n-1)which actually calls the same method and messes up the output! Instead save the result and the print/return it:res = n*recursive(n-1); print(f"Recursion result {res}"); return res(<--pseudo code not python)