Python if/else遵从错误的分支

2024-03-28 22:31:42 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在为一个学校项目编写一个交互式小说游戏,出于某种原因,当我尝试使用带有输入(或原始输入)的if/else语句时,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。有人能帮我解决这个错误吗?你知道吗


Tags: orandthetoinyoutrueif
3条回答

我相信你的问题在于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"是非空的,因此在if语句中转换为True。这是因为python中的or操作符是一个布尔值,或者,如果操作符的任意一方(转换为布尔值)为true,则表达式为true。解决这个问题的最简单方法(即最少的代码重构)是一系列==

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

还有其他的,但是对于像你这样的简单的is程序来说,这应该可以做到。如果您需要做越来越复杂的匹配,您应该研究字符串运算符。例如,您的表达式可以重写为if "yes".startswith(choice2.lower()): #...,但是在不理解它的情况下不要使用它。对于像您这样大小的程序,链式的==就可以了。希望这有帮助!你知道吗

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

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

或者这种更像Python的方法:

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

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

如果你的陈述是错误的,它们应该是这样的:

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

或者像这样:

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

Python将非空字符串视为true,例如,“Yes”被认为是true。所以如果你写choice == "yes" or "Yes",表达式总是真的,因为即使choice == "yes"不是真的,"Yes"也会被认为是真的。你知道吗

相关问题 更多 >