我的python代码有错误,但仅在try-except循环中。

时间:2018-11-27 22:31:38

标签: python

我的python代码在try-except循环中有一些错误。如果输入的输入不是yes或no,则它将首先打印“ yes”答复输出,然后在回答问题后,如果不输入yes或no,则会显示输出。这是代码:

playAgain = None

while playAgain != "Yes" or "No" or "yes" or "no" or "y" or "n":
    try:
            playAgain = str(input("Do you want to play again? Enter Yes or No: "))         
            if playAgain == "Yes" or "y" or "yes":
                displayIntro()
            elif playAgain == "No" or "no" or "n":
                print("Oh, well. The magic 8 ball will see you next time...")
                sys.exit()
    except:
                print("That wasn't yes or no, idiot. The magic 8 ball will not give a fortune to such an imbocile.")

请帮忙,谢谢!

1 个答案:

答案 0 :(得分:4)

playAgain != "Yes" or "No" or "yes" or "no" or "y" or "n"

这不是正确的方法。

playAgain != "Yes"时,您需要对其余表达式执行相同的操作。因此,执行您打算做的事情的有效方法如下:

playAgain != "Yes" or playAgain != "No" or playAgain != "yes" or playAgain != "no" or playAgain != "y" or playAgain != "n"

但这很丑陋,而且时间太长。

相反,使用

playAgain not in ["Yes", "No", "yes", "no", "y", "n"]

在Python中,我们有一些便捷的方法来处理此类问题。您可以使用in运算符来检查所讨论的字符串在可能值列表中是否存在(或不存在)。读起来也非常好:“如果playAgain(不在[此值列表]中”)。

您甚至可以操纵输入,以便于使用。也就是说,您降低所有字母,并且不检查是否区分大小写(如果您真的不关心区分大小写的输入;您是否真的在意YesyEs? ):

playAgain.lower() not in ["yes", "y"]

类似的事情应该做:

while True:
    playAgain = str(input("Do you want to play again? Enter Yes or No: "))         

    if playAgain.lower() in ["yes", "y"]:
        # do something with your yes input. Consider `break` out of the endless loop.
    elif playAgain.lower() in ["no", "n"]:
        # do something with your no input. Consider `break` out of the endless loop.
    else:
        print("That wasn't yes or no.")

请注意,以上循环是无限的。您需要根据程序逻辑进行分组。也就是说,当您需要摆脱无限循环时,需要在地方放置break语句。