简体   繁体   中英

How to understand the output of this Python code involving recursion?

Here is the code snippet:

(This is just a sample code I have written to understand how recursion works, hence the var and function names.)

def b(t):
t += 1
print("t ", t)
for i in range(2):
    if (t <= 3):
        b(t)
print("t_again ", t)
return t

def a(): // call this function from main
    t = 0
    t1 = b(t)
    return t1

Here's what I thought would be the output:

t 1
t 2
t 3
t 4
t_again 4 //execute return statement after this

But the actual output was:

t  1
t  2
t  3
t  4
t_again  4 # 1
t  4
t_again  4
t_again  3
t  3
t  4
t_again  4
t  4
t_again  4
t_again  3
t_again  2
t  2
t  3
t  4
t_again  4
t  4
t_again  4
t_again  3
t  3
t  4
t_again  4
t  4
t_again  4
t_again  3
t_again  2
t_again  1

I don't understand why the recursion isn't stopping after printing the line with comment number 1 above.

Also, why is the value of t decreasing at the end?

I think the issue is I didn't understand the concept of recursion properly.

because this part will print 1

print("t ", t)
for i in range(2):
    if (t <= 3):
        b(t)
print("t_again ", t)

then go to function b again and print 2.

after going to the maximum recursion debt in your case 4 it will print "4 again" and return, after returning from recursion depth 4 your code is in depth 3 and with print "4", "4 again", "3 again" and return to depth 2 and do it all over again

This does not explain recursion, but comments whit python are typed as "#" and not as "//". Python is not c++/c/javascript/java.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM