Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Recursive function in while loop changing variable [python]

I had a student give me the following code:

def addtwo():
 numb=input("enter any number")
 add=int(numb)+2
 print(add)
 inp = input("do you wish to enter again")
 while inp=="yes":
       addtwo()

After the first iteration, if the user inputs anything other than 'yes', the body of the while loop doesn't execute, as expected. But if we enter 'yes', it executes (again, as expected) and prompts "enter any number", but in the second iteration, even if the user enters anything other than 'yes' on "do you wish to enter again", the body of the while loop STILL executes. Now I ran the debugger on it, and found out that the value of inp just changes to 'yes' when executing line 5. Before execution of the line, the value of inp, according to the debugger is still whatever the user entered. Why is that so?

Now I looked it up here, but couldn't find any explanation, though I found a way to work around it by adding a return before the call to addtwo() in the body of the while loop (I found it here: Calling a function recursively for user input) but couldn't understand why the value of inp just change in the local stack, and how the return statement fixes it?

Here's the working code:

def addtwo():
     numb=input("enter any number")
     add=int(numb)+2
     print(add)
     inp = input("do you wish to enter again")
     while inp=="yes":
           return addtwo()

And, to add to my puzzle, the code just works fine if we use an if statement instead of while.

like image 849
Umair Rafique Avatar asked Jan 26 '26 15:01

Umair Rafique


1 Answers

Summary

This is because once you have entered yes once, that function will loop forever, regardless of what the next recursive call does.

You can fix your code by changing:

while inp == "yes":
    add_two()

to

if inp == "yes":
    add_two()

Walk through

  • add_two is called
  • the user enters a number
  • they are asked if they wish to continue
  • they enter "yes"
  • while imp == "yes" will now always be true
  • it calls add_two
    • they enter a number
    • they enter "no"
    • the loop doesn't run, so returns back to the first call of add_two
  • back into the while loop. it still evaluates to true, so continues calling add_two

The return statement

By default in python, functions which do not return anything, actually return None. This means you call add_two, and if the user does not enter "yes" when prompted, it will return, which will then force the first call to also return.

like image 108
dangee1705 Avatar answered Jan 29 '26 04:01

dangee1705



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!