3

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?

1
  • There are two recursive calls in your function. Plus you're using a while loop inside the function so the while test is always true for calls having x < 10 Commented Aug 13, 2019 at 10:43

2 Answers 2

4

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.

Sign up to request clarification or add additional context in comments.

Comments

0

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)

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.