-1

I have created a very basic function that will return "Yes1" when the user says "Yes" and "No1" when the user says "No", I also have a line that makes the function reset itself when the user enters an unrecognized answer. This function works fine except when I enter multiple invalid answers, at which poitn it only responds "No1", even if I put "Yes". The code is here:

print ("Welcome to the automated phone trouble shooting service, please answer with either 'Yes' or 'No'")
print("unless the questions asks otherwise")

print ("Welcome to the automated phone trouble shooting service, please answer with either 'Yes' or 'No'")
print("unless the questions asks otherwise")

def q1():
    answer1=input("Is the phone wet?")
    if answer1== "Yes":
        return True
    elif answer1== "No":
       return False
    else:
        print("Invalid answer, restarting now")
        q1()

if q1()==True:
    print ("Yes1")
else:
    print ("No1")
Bhargav Rao
  • 50,140
  • 28
  • 121
  • 140

1 Answers1

2

To make the behavior of your function consistent for invalid inputs, you should return the returned value from the recursive call:

def q1():
    answer1=input("Is the phone wet?")
    if answer1== "Yes":
       ...
    elif answer1== "No":
       ...
    else:
        ...
        return q1()
#       ^^^^^^

If you don't, the main call will return None if an invalid input is entered.

You could avoid using recursion by setting up a while loop instead.

Have a look at Asking the user for input until they give a valid response

Community
  • 1
  • 1
Moses Koledoye
  • 77,341
  • 8
  • 133
  • 139