Python if / else推迟到错误的分支

时间:2017-03-19 16:00:35

标签: python if-statement

我正在为一个学校项目编写一个互动小说游戏,出于某种原因,当我尝试将if / else语句与input(或raw_input)一起使用时,if else语句会推迟到错误的分支,而不管是什么我输入。以下是有问题的代码:

print( """ 
    You enter the room to the south. 
    Upon entering you mark that it is pitch black, 
    and if you were in the famous text adventure Zork, 
    you would be likely to be eaten by a grue. Thank 
    the programmer for small favors. Unlike in that game, 
    you have a candle, a single stick of 100-year-old 
    dynamite, and that matchbook from earlier. 
    You just knew that would be useful! The candle and 
    the dynamite have the same shape, size, and weight.""") 

choice1 = True 

while choice1 == True: 
    choice2 = input("Will you strike a match? ") 

    if choice2 == "Yes" or "yes" or "y": 
        print("""
            It flickers for a second. You can kind of make 
            out which is which, but alas! They are both 
            covered in red paper! You are beginning to sweat 
            from the nervousness.""") 

        choice1 = False 

    elif choice2 == "No" or "no" or "n": 
        print(""" 
            Okay. I can wait, you aren’t leaving this room until 
            you light a match. You will eventually light a match, 
            but I can wait until you do.""") 
        choice1 = True 
    else: choice1 = True

if / else语句正在处理我键入的任何内容,就好像我键入了yes一样。任何人都可以帮我解决这个错误吗?

3 个答案:

答案 0 :(得分:3)

您的if语句错误,它们应如下所示:

if choice in ["Yes", "yes", "y"]:
    …

或者像这样:

if choice == "Yes" or choice == "yes" or choice == "y":
    …

Python将非空字符串视为true,例如“是”被认为是真的。因此,如果您编写choice == "yes" or "Yes",则表达式始终为true,因为即使choice == "yes"不为真,"Yes"也会被视为真。

答案 1 :(得分:1)

if choice2 == "Yes" or "yes" or "y"不能像你想象的那样工作。在第一个语句choice2 == "Yes"之后,它就像是在询问if "yes"if "y"。除非字符串为空,否则字符串上的if语句将始终返回true。要解决此问题,您需要

if choice2 == "Yes" or choice2 == "yes" or choice2 == "y":

或更多pythonic方法:

if choice2 in ["Yes", "yes", "y"]:

将检查字符串是否在该数组中。 当然同样的事情适用于elif choice2 == "No" or "no" or "n":,它的当前形式也总是返回true。

答案 2 :(得分:1)

我相信您的问题出在if声明中。条件,例如if choice2 == "Yes" or "yes" or "y"。这看起来会检查choice2"Yes"还是choice2"yes"还是choice2"y",但它不会。问题是or语句。代码中的if语句可以写为if (choice2 == "Yes") or ("yes") or ("y")并具有相同的含义。这使得更容易看到,即使choice2不等于Yes,表达式也将为真,因为字符串"yes"非空,因此转换为{{1在True语句中。这是因为python中的if运算符是一个布尔OR,因此如果运算符的任何一侧(转换为布尔值)为true,则表达式为。解决此问题的最简单(即最少代码重构)方法是一系列or

==

还有其他人,但这应该可以解决一个像你这样的简单程序。如果您需要进行越来越复杂的匹配,则应该查看字符串运算符。例如,您的表达式可以重写为if choice2 == "Yes" or choice2 == "yes" or choice2 == "y": #...,但不要在不理解的情况下使用它。对于你的大小的程序,链式if "yes".startswith(choice2.lower()): #...将会很好。希望这有帮助!