如果条件即使是真的,Python也会跳过

时间:2016-12-10 16:05:53

标签: python if-statement

我正在向LPTHW学习,基本上它是一个基于文本的房间游戏。

class Riddle_Room(Room):
    def activate(self):
        global current_room
        print "Riddle room query"
        current_room = "riddle_room"
        self.ip = raw_input("> ")
        self.count = 3
        print self.ip
        if "back" in self.ip:
            rm.back()
        elif "yes" in self.ip:
            while self.count > 0:
                print "Riddle"
                self.answer = raw_input("> ")
                if self.answer == "answer":
                    print "You got that right!"
                    rm.enter()
                else:
                    print "Try again!"
                    self.count -= 1
            print "No choices left."
            quit()
        else:
            print "Invalid command."

当我第一次进入这个房间时,它会问我一个查询,如果我说“是”它会问我这个谜语。答案是“回答”并进入,将我带到下一个房间。当我回到这个房间时,它再次询问我的谜语房间查询,但这次如果我输入“返回”,它会说无效命令,这是else案例。它会跳过第一个if。我添加了print self.ip来检查self.ip是否正在更改为"back"并且确实如此!

2 个答案:

答案 0 :(得分:0)

这是因为您没有在循环中定义后退命令。这是您应该更改代码的方式:

<!-- Your HTML was not correct for a few reasons:
    1. You had inline event handlers (onclick)
    2. You had attributes with no values (alt="", class="")
    3. You were setting style information (height and width) using HTML attributes
       3a. That should be done with CSS
       3b. Even if you were going to do it in HTML, you included "px" in the values which is wrong
    4. You can't have the link that toggles the visibility of the divs in one of the divs that 
       will wind up being hidden because you'll hide the link that brings it back.
-->

<div>
    <a href="#document_body" id="uvp_bar_link">Toggle divs</a>
</div>

<div class="uvp_bar_display" id="uvp_bar">
    <img id="uvp_bar_image" src="/asset/image/sea_foam_minimized.gif" alt="image 1">
</div>

<div class="uvp_display" id="uvp">
  <img alt="sea foam" id="uvp_image" src="/asset/image/image.jpg">
</div>

答案 1 :(得分:0)

在脑海中练习完成代码。

第一次输入“是”时,您将在elif "yes" in self.ip下输入代码部分。在此部分代码中,将向您询问三次答案。但是这部分代码不包含“back”一词的检查。因此,您将被要求三次答案,唯一可接受的答案是“回答”。

换句话说,“back”仅被识别为对提示“Riddle room query”的响应,而不是对提示“Riddle”的响应。