使用else返回函数命令顶部时返回不同的答案

时间:2016-10-03 08:08:51

标签: python function

我创建了一个非常基本的功能,当用户说“No”时会返回“Yes1”,当用户说“No”时会返回“No1”,我还有一条线让用户进入时自动复位一个未被承认的答案。此功能正常工作,除非我输入多个无效答案,即使我输入“是”,它只响应“No1”。 代码在这里:

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")

1 个答案:

答案 0 :(得分:2)

要使函数的行为与无效输入保持一致,您应该从递归调用中return 返回值

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

如果不这样做,如果输入的输入无效,主呼叫将返回None

您可以通过设置while循环来避免使用递归。

查看Asking the user for input until they give a valid response