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.
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
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With