Python LPTHW 练习36

2024-09-30 04:35:23 发布

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

我是编程新手,正在学习Python的书《艰难的学习Python》。我在练习36,我们被要求写我们自己的简单游戏。在

http://learnpythonthehardway.org/book/ex36.html

(问题是,当我在走廊里(或者更准确地说,在“选择”中),当我写下“门”时,游戏的反应就好像我说了“老人”的“男人”一样

我做错了什么?)在

编辑:我不应该在选项中写“如果”老人“或“男人”,而是在每个选项后加上“选择”。在

然而,下一个问题。。那人从不站起来骂我,总是皱着眉头。为什么游戏不进行到那个elif?在

experiences = []    
def choices():
        while True:
            choice = raw_input("What do you wish to do? ").lower()

            if "oldman" in choice or "man" in choice or "ask" in choice:
                print oldman
            elif "gate" in choice or "fight" in choice or "try" in choice and not "pissedoff" in experiences:
                print "The old man frowns. \"I said, you shall not pass through this gate until you prove yourself worthy!\""
                experiences.append("pissedoff") 
            elif "gate" in choice or "fight" in choice or "try" in choice and "pissedoff" in experiences and not "reallypissed" in experiences:
                print "The old man is fed up. \"I told you not to pass this gate untill you are worthy! Try me again and you will die.\""
                experiences.append("reallypissed")

            elif "gate" in choice or "fight" in choice or "try" in choice and "reallypissed" in experiences:
                print "The old man stands up and curses you. You die"
                exit()


            elif "small" in choice:
                print "You go into the small room"
                firstroom()
            else: 
                print "Come again?"

编辑:修正了!!

^{2}$

谢谢你的帮助:)。在


Tags: orandinyou游戏notprinttry
2条回答

The problem is, when I'm in the hallway (or more precisely, in 'choices') and I write 'gate' the game responds as if I said "man" of "oldman" etc.

解释

你所做的被Python视为:

if ("oldman") or ("man") or ("ask" in choice):

如果这3个条件中的任何一个都是"truthy" value,则计算结果为True。像“oldman”和“man”这样的非空字符串的计算结果为True。所以这就解释了为什么你的代码会表现出这样的行为。在

测试选项是否在选项列表中:

你在找

^{pr2}$

或者,至少:

if 'oldman' in choice or 'man' in choice or 'ask' in choice

仔细查看您的条件评估:

    if "oldman" or "man" or "ask" in choice:

这将首先计算"oldman"是否是True,恰好是这样,if条件的计算结果是True。在

我想你的目的是:

^{pr2}$

或者,您可以使用:

    if choice in ["oldman" , "man", "ask" ]:          

一个警告是,对于这个方法,它寻找的是精确匹配,而不是子字符串匹配。在

相关问题 更多 >

    热门问题