Python while语句不起作用

时间:2013-08-23 16:19:11

标签: python while-loop

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

North通往花园。  南通往厨房。  东通往餐厅。  West通往起居室。

应该提示玩家指示方向并回复 在那个方向偏离的位置。例如,如果玩家进入 北方,该计划应该回应:北方通往花园。如果 玩家进入无效方向,程序应忽略输入 并要求另一个方向。该程序将在播放器结束时结束 进入退出。

我的问题是当用户输入"退出"该计划不退出。所以我不明白为什么我的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")

3 个答案:

答案 0 :(得分: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: except块:我们不需要先前检查字典中的成员资格,这样我们就可以了:

#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

此时我觉得删除任何cargo code很好,我们为什么要使用:

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

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

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: ")

这里我也删除了位置变量,在这种情况下它是不需要的,因为direction是关键信息。当尝试打印不存在的Key时,仍然会引发KeyError,这样就太酷了!

还要注意,如果您想要调用.lower(),您首先不需要设置变量,您可以在访问字典时这样做:

print game[direction].lower()

答案 1 :(得分: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..."

答案 2 :(得分:0)

如果你还是等待输入,那么简单地为他们退出的情况做一个“if”会更容易,对于它是一个实际方向和一个简单的“其他”的情况来说是一个“elif”如果他们输入乱码就结束。