0

我有一个家庭作业问题。我应该创建一个字典来表示以下内容:

北通向花园。南通向厨房。东通向餐厅。西通向客厅。

应提示玩家输入方向,并以该方向关闭的位置进行响应。例如,如果玩家进入北,程序应该响应:北通向花园。如果玩家输入了一个无效的方向,程序应该忽略输入并要求另一个方向。当玩家进入退出时程序将结束。

我的问题是当用户输入“退出”时程序不会退出。所以我不明白为什么我的 while 语句不起作用。这是我的代码:

 #Create a Dictionary to represent the possible
 #exits from a location in an adventure game

 game = {"north" : "North leads to garden.",
    "south" : "South leads to the kitchen.",
    "east" : "East leads to the dining room.",
    "west" : "West leads to the living room."}
 print "Press quit to exit"

 direction = raw_input("Enter your direction: ")
 while direction != "quit":
     direction = direction.lower()

     if direction in game:
         location = game[direction]
         direction = direction.lower()
         print location


     if direction not in game:
         direction = raw_input("Enter your direction: ")
         location = game[direction]
         direction = direction.lower()
         print location

     raw_input("\n\nPress quit to exit")
4

3 回答 3

3

由于您如何缩进代码,我无法确定,但我认为问题在于:

raw_input("\n\nPress quit to exit")

应该:

direction = raw_input("\n\nPress quit to exit")

但是,有几件事是错误的。

if direction not in game:        
     direction = raw_input("Enter your direction: ")
     location = game[direction]
     direction = direction.lower()
     print location

在代码的这一点上,输入的方向不是退出,也不是在字典中,所以如果我们此时输入退出,我们会得到:

Traceback (most recent call last):
  File "homework.py", line 21, in <module>
    location = game[direction]
KeyError: 'quit'

我们可以通过两种方式解决这个问题,或者我们可以尝试然后处理异常,或者我们可以再次检查字典的成员资格。例如:

if direction not in game:        
     try:
         direction = raw_input("Enter your direction: ")
         location = game[direction]
         direction = direction.lower()
         print location
     except KeyError:
          pass

我只使用except KeyError了你不想让所有异常静音的情况,因为你会在调试时丢失有价值的信息。您已经表明您知道如何检查它是否在字典中,因此无需再次显示该方法。

所以如果我们把它放在一起,我们会得到:

#Create a Dictionary to represent the possible
#exits from a location in an adventure game

game = {"north" : "North leads to garden.",
        "south" : "South leads to the kitchen.",
        "east" : "East leads to the dining room.",
        "west" : "West leads to the living room."
}

direction = raw_input("Enter your direction: ")

while direction != "quit":
    direction = direction.lower()
    if direction in game:
        location = game[direction]
        direction = direction.lower()
        print location

    if direction not in game:        
         try:
             direction = raw_input("Enter your direction: ")
             location = game[direction]
             direction = direction.lower()
             print location
         except KeyError:
             pass

    direction = raw_input("\n\nPress quit to exit: ")

一旦我们到达这一点,我们应该看看程序是如何运行的,我们可以看到我们在脚本执行期间多次要求用户输入,设置相同的变量。现在我们有了一些工作,我们应该考虑删除所需的调用。由于我们添加了try: exceptbloc: 我们不需要先前检查字典中的成员资格,这给我们留下了:

#Create a Dictionary to represent the possible
#exits from a location in an adventure game

game = {"north" : "North leads to garden.",
        "south" : "South leads to the kitchen.",
        "east" : "East leads to the dining room.",
        "west" : "West leads to the living room."
}    
# Initialize the direction variable
direction = ""
# Keep looping user types in quit
while direction != "quit":   
         try:
             # Take the user input at the start of the loop
             direction = raw_input("Enter your direction Or quit to exit: ")
             # Get the location string if it exists
             location = game[direction]
             # Make the string lower case
             direction = direction.lower()
             # Display location message
             print location
         # If this KeyError is raised user has entered a location not in the
         # dictionary
         except KeyError:
             # We can do nothing because we are just going to get new user input
             # next time the loop runs!
             pass

在这一点上,我认为删除任何货物代码都很好,我们为什么要使用:

location = game[direction]
direction = direction.lower()

如果我们想要小写的方向,我们可以将它们定义为上面十行的小写,其次一直询问相同的消息很烦人,所以我们将询问一个 septate quit 消息。因此,在删除不需要的行之后,我们得到:

game = {"north" : "North leads to garden.",
       "south" : "South leads to the kitchen.",
       "east" : "East leads to the dining room.",
        "west" : "West leads to the living room."
}

direction = ""

while direction != "quit":   
         try:
             direction = raw_input("Enter your direction: ").lower()
             print game[direction]
         except KeyError:
             direction = raw_input("The direction you have entered is invalid\nEnter a direction or quit to exit: ")

在这里,我还删除了 location 变量,在这种情况下它是不需要的,因为方向是关键信息。尝试打印不存在的 Key 时仍然会引发 KeyError ,这很酷!

还要注意,如果你想打电话.lower(),你不需要先设置变量,你可以在访问字典时这样做:

print game[direction].lower()
于 2013-08-23T16:40:15.493 回答
1

与这里的其他人一样,由于缺少缩进,我不能完全确定您的代码正在尝试做什么,但是在黑暗中尝试一下,使用一种方法来获取方向可能会更容易处理不好的方向。所以你的代码可以变成:

   #Create a Dictionary to represent the possible
   #exits from a location in an adventure game

def get_dir():
    good_answers = ["north", "south", "east", "west", "quit"]
    direction = raw_input("Enter your direction: ").lower()
    while direction not in good_answers:
        direction = raw_input("Bad direction, try again: ").lower()
    return direction

game = {"north" : "North leads to garden.",
    "south" : "South leads to the kitchen.",
    "east" : "East leads to the dining room.",
    "west" : "West leads to the living room."}

print "Press quit to exit"
direction = get_dir()
while direction != "quit":
    print game[direction]
    direction = get_dir()

print "Quitting..."
于 2013-08-23T17:23:46.880 回答
0

如果您仍然等待输入,那么简单地为他们退出的情况做一个“if”会更容易,如果他们退出的情况是一个“elif”,如果它是一个实际方向,最后一个简单的“else”会更容易输入乱码。

于 2013-08-23T17:16:07.013 回答