Python 名称错误 : name 'north' is not defined for Text Game

标签 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

感谢您的帮助

最佳答案

这一行

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/

相关文章:

python - 在 xarray 中导入和解码数据集以避免冲突 _FillValue 和 missing_value

python - 对于检测到的形状略有变化的 OpenCV,Hu 矩是否保持不变?

python - 如何列出discord.py 中的所有角色

python - Google App Engine TextProperty 和 UTF-8 : When to Encode/Decode

function - 是否可以在 Tableau 中创建用户定义的函数?如果是,它使用什么编码语言?

python - io 重定向的奇怪行为

c - 使用 #ifndef 指令在多个 C 代码中重新定义符号

perl 检查嵌套哈希引用

重定向后不包含 jquery(primefaces)

Oracle:列定义不明确