Python While 循环问题。如何让我的 while 循环检测一个人是否说是、y、n 或否?

时间:2021-04-12 22:22:41

标签: python loops input while-loop

我创建了一个 while 循环,它基本上接受用户的输入,它应该检测用户何时没有输入 yes、y、no、n,然后重新启动进程。我尝试使用 charArt(0) 是因为我试图让它检测第一个字母 y 或 n,以防用户输入 y 或 yes 或 n、no,并且它能够检测到是或否。但它给了我一个错误。

   wants_to_play = "x"
        while wants_to_play.charAt(0) != "y" and wants_to_play.charAt(0) != "n":
            wants_to_play = input("Do you want to play? (Yes/No): ").lower()
            if wants_to_play == "y" or wants_to_play == "yes":
                print("Let's play!")
            elif wants_to_play == "n" or wants_to_play == "no":
                print("Aww too bad, maybe next time!")
                exit()
            elif wants_to_play == 'exit':
                break
            else:
                print("There has been error, type yes or no: ")
                print("Or you can type in exit to end the game!")

2 个答案:

答案 0 :(得分:0)

您应该按照评论中的建议使用 startswith()。另一个错误是,当您似乎想使用“或”时,却使用了“和”。

while !wants_to_play.startswith("y") or !wants_to_play.startswith("n"):
    ...

应该做得很好。

答案 1 :(得分:0)

似乎每个人都回答了这个问题,但是我会提供不同的解决方案。我发现在 wants_to_play 循环和 while 语句中检查 if 是否以“y”开头有点奇怪。在这种情况下,我个人会使用递归:

def ask_to_play():
    wants_to_play = input("Do you want to play? (Yes/No): ").lower()
    if wants_to_play.startswith("y"):
        print("Let's play!")
    elif wants_to_play.startswith("n") or wants_to_play == 'exit':
        print("Aww too bad, maybe next time!")
        exit()
    else:
        print("There has been error, type yes or no: ")
        print("Or you can type in exit to end the game!")
        ask_to_play()
ask_to_play()

但这工作得很好:

wants_to_play = "x"
while wants_to_play[0] != "y" and wants_to_play[0] != "n":
    wants_to_play = input("Do you want to play? (Yes/No): ").lower()
    if wants_to_play == "y" or wants_to_play == "yes":
        print("Let's play!")
    elif wants_to_play == "n" or wants_to_play == "no":
        print("Aww too bad, maybe next time!")
        exit()
    elif wants_to_play == 'exit':
        break
    else:
        print("There has been error, type yes or no: ")
        print("Or you can type in exit to end the game!")