我为基于文本的游戏编写了此代码,但收到错误消息
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比输入更安全。
一种替代方法是捕获这样的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 - Python NameError:未为文本游戏定义名称“north”,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/19040012/