1

我为我的基于文本的游戏制作了这段代码,我收到一条错误消息

 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

谢谢你的帮助

4

2 回答 2

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 比 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
于 2013-09-26T23:18:14.947 回答
0

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

input()相当于eval(raw_input()); 因此,您的代码在您输入时试图找到一个名为“north”的变量。

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


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

你可以总结你的代码:

print Map.get(userInput, 'Please specify a various direction')
于 2013-09-26T22:54:31.870 回答