3

Beginner programmer here, using Python 2.7.10. I've got this code:

def yesno():
    answer = raw_input("(Y/N) > ").upper()
    if answer == "Y":
       return True
    elif answer == "N":
       return False
    else:
       yesno()

if yesno():
    print("Yes")
else:
    print("No")

I'm trying to call the function within itself to 'restart' it if the conditions aren't met. The problem I have is that when I restart it more than once it will not return the value it should. For example, if I input "X" the first time but "Y" the second time, it will still print "No" in the end. Is there a better way to restart a function within itself?

1
  • 2
    return yesno() instead of yesno() Commented Nov 4, 2015 at 2:46

3 Answers 3

3

Try this:

def yesno():
    answer = raw_input("(Y/N) > ").upper()
    if answer == "Y":
       return True
    elif answer == "N":
       return False
    else:
       return yesno()     # CHANGE IN THIS LINE.

if yesno():
    print("Yes")
else:
    print("No")

It should work. I just now tested it.

Explanation:

When the if statement called the function for the first time, it is expecting a value to be returned. When the first input is X, the flow of the function reaches the else part and calls yesno() again to ask for another input. When user inputs an Y, it returns TRUE not to the if-statement that called it but to the first function call.

This then becomes something like this:

if answer == "Y":
    return True
elif answer == "N":
    return False
else:
    True     # Notice that the function is NOT returning this True.

Since, the first call of the function is NEVER returning anything, your if-statement is NOT getting true. Hope this helps in the understanding!

0
0

There's a better way to do this without a recursive function. Just throw an error, or print a message if the user doesn't enter the correct input:

def yes_or_no(prompt):
    user_input = raw_input(prompt):
    if user_input == "y":
        return True
    elif user_input == "n":
        return False
    else:
        # Display a helpful message here.

There are a few advantages to this method, rather than the recursive function. If you use a recursive function, every time you re-call it, you keep pushing to the stack frame, and once you've recursed over 1000 times, your program will throw an error.

It's just best to display a message, and ask for input again.

If you really want the recursive solution, then just change the recursive call from this:

yesno()

To this:

return yesno()
0

Your mistake is simply that you aren't returning the value from the recursive call. Change the else branch to return yesno() and it will work fine. You could do this with a while loop instead of a function:

answer = ''
while answer != 'Y' and answer != 'N':
   answer = raw_input("(Y/N) > ").upper()

Not the answer you're looking for? Browse other questions tagged or ask your own question.