我为基于文本的游戏编写了此代码,但收到一条错误消息
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
感谢您的帮助
最佳答案
这一行
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
关于Python 名称错误 : name 'north' is not defined for Text Game,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19040012/