Apparently a straightforward recursive function ends in an infinite loop

I wrote the following code:

def incr_num(x, y): while x <= y: print x incr_num(x+1, y) 

When I call it like

 incr_num(1, 10) 

it falls into an infinite loop and gives this conclusion:

 1 2 3 4 5 6 7 8 9 10 10 10 10 10 10 10 (number 10 keeps repeating) 

I expected him to print the numbers 1-10. I can’t understand why this is not so. Can someone please tell me why this is happening.

I am using python2.7.

+5
source share
4 answers

The correct version is:

 def incr_num(x, y): if x <= y: print x incr_num(x+1, y) 

Note that x is printed no more than once for each recursive function call.

UPDATE: The reason your function doesn't work is because incr_num(10,10) prints 10 and then calls incr_num(11,10) , which returns immediately. After that, incr_num(10,10) continues. It will not exit the while and continue the next iteration, typing 10 again and calling incr_num(11,10) . As you can see, this cycle does not end.

+4
source

incr_num(x+1, y) continues to receive the call until x == y , and then the recursion ends, then you return to the previous execution, where x=9 , so x still has the value that it passed, and x <= y is not false, so recursion happens again and prints 10

At least you will need x+=1 after this recursive call.

I would not call the while loop inside recursion simple;) If in your base case, to complete the recursion, you want if x<=y

+4
source

If your loop runs forever, it should mean that the condition x <= y always True . Consider this:

 while x <= y: print x 

This is a simplified version of your code, but it is essentially what you do.

Try:

 def incr_num(x, y): if x <= y: print x incr_num(x+1, y) 

It prints the numbers 1 through 10 .

+4
source

Your condition should be an if condition instead of a while loop, because you do not change the value of x inside the while loop, and each time the condition becomes true and makes a recursive call.

Here is the revised version

 def incr_num(x, y): if x <= y: print x incr_num(x+1, y) 
+3
source

Source: https://habr.com/ru/post/1273805/


All Articles