简体   繁体   中英

Control flow in recursion python

I created the following function:

def test_recursion(x):
    print(x)
    while x < 10:
        test_recursion(x+1)
        test_recursion(x+2)
    print("end of function reached")

test_recursion(1)

What I don't understand is why after x reaches 10 and the end of function print statement is reached, it keeps printing 11 then 10 in an infinite loop.

Should the program not end after 10 is printed?

You are not changing the value of x in your while loop. As long as x is less than 10, it will loop forever. Consider using an if statement instead.

the first 9 levels of your recursion depth are always less than 10

while x < 10

nothing is changing x to anything else

If you want to limit the recursion, re-structure to this:

while x < 10:
    x = x + 1
    test_recursion(x)
    test_recursion(x+1)

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