将变量设置为仅接受 python 上的某些字符串并使用 if/else 中断 while 循环

set a variable to only accept certain strings on python and break while loops using if/else

我目前正在编写需要重复的代码,但前提是用户希望它 repeated.I 已将代码放入 "while True" 循环中并尝试使用 if 语句来如果用户输入 "yes" 则重复代码,如果用户输入 "no" 则中断循环,但是无论用户输入什么,循环都不会中断。这是我试图开始工作的内容:

while True:
    question=input("do you like maths?")
    re_do=input("Would you like to check anything else?")
    if re_do.lower=="no":
        break
    elif re_do.lower=="yes":
        continue

如果他们输入 "yes" 或 "no" 以外的内容,我还需要重复这个问题,所以我想知道是否有办法将变量设置为只接受 "yes" 或 "no" 所以我可以使用 "try" 和 "except".

这个答案是基于你原来的问题,我不确定我是否完全理解。另外,在您的评论中,我试图了解您想要实现的目标,但我不确定我是否明白了,但我希望它能有所帮助:

while True:
    question=input("do you like maths?")
    re_do=input("Would you like to check anything else?")
    if re_do.lower() =="yes":
        continue
    elif re_do.lower() =="no":
        print "Goodbye!"
        break
    elif re_do.lower() !="no" and re_do.lower() !="yes":
        x = input("Yes or No answer only: ")
        if x == "yes":
            continue
        else:
            print "Goodbye"
            break

在评论部分和 @Joe R 的各种用户的帮助下,我找到了这个问题的答案:

while True:
    question=input("do you like maths?")
    while True:
        re_do=input("Would you like to check anything else?")
        if re_do.lower=="no":
            quit()
        elif re_do.lower=="yes":
            break
        elif re_do.lower() !="no" and re_do.lower() !="yes":
            print("Yes or No answer only: ")
            continue