Python NameError:未为Text Game定义名称“north”

时间:2013-09-26 22:53:13

标签: python defined

我为基于文本的游戏制作了此代码,我收到错误说

 line 1, in <module>
userInput = input("Please enter a direction in which to travel: ")
 File "<string>", line 1, in <module>
NameError: name 'north' is not defined

这是我的代码

userInput = input("Please enter a direction in which to travel: ")
Map = {
    'north':'that way leads to the kitchen', 
    'south':'that way leads to the dining room', 
    'east':'that way leads to the entry', 
    'west':'that way leads to the living room'
}
if userInput == north:
    print Map['north']
elif userInput == south:
    print Map['south']
elif userInput == east:
    print Map['east']
elif userInput == West:
    print Map['west']
elif userInput == '':
    print "Please specify a various direction."
else:
    quit

感谢您的帮助

2 个答案:

答案 0 :(得分:2)

这一行

if userInput == north:
    ...

询问名为userInput的变量是否与变量north相同。

但是你还没有定义一个名为north的变量。该行应与此类字符串'north'进行比较。

if userInput == 'north':
    ...

但是,您可以像这样在字典键中测试用户输入。我已将你的常数改为全部大写。

MAP = {
    'north':'that way leads to the kitchen', 
    'south':'that way leads to the dining room', 
    'east':'that way leads to the entry', 
    'west':'that way leads to the living room'
}
userInput = raw_input("Please enter a direction in which to travel: ")
if userInput in MAP.keys():
    print MAP[userInput]

另外,正如另一个答案所述,raw_input比输入更安全。

另一种方法是像这样捕获KeyError。

MAP = {
    'north':'that way leads to the kitchen', 
    'south':'that way leads to the dining room', 
    'east':'that way leads to the entry', 
    'west':'that way leads to the living room'
}
userInput = raw_input("Please enter a direction in which to travel: ")
try:
    print MAP[userInput]
except KeyError:
    print 'What?'

或重复直到这样提供有效输入(并使其不区分大小写):

MAP = {
    'north':'that way leads to the kitchen', 
    'south':'that way leads to the dining room', 
    'east':'that way leads to the entry', 
    'west':'that way leads to the living room'
}
while True:
    userInput = raw_input("Please enter a direction in which to travel: ").lower()
    try:
        print MAP[userInput]
        break
    except KeyError:
        print '%s is not an option' % userInput

答案 1 :(得分:0)

使用Python 2时,您应该始终使用raw_input()来获取用户的输入。

input()相当于eval(raw_input());因此,当您输入时,您的代码会尝试查找名为“north”的变量。

但是,在Python 3中,input()与{2}中的raw_input()行为相同。


您还应该将输入与字符串进行比较,而不是将您创建的变量进行比较。例如,if userInput == north应为if userInput == 'north'。这使得'north'成为一个字符串。

您可以通过以下方式总结您的代码:

print Map.get(userInput, 'Please specify a various direction')