首页 > 解决方案 > 获取“NameError:名称'room_path'未定义”

问题描述

这是我遇到问题的代码。我正在使用 Python 3.6。

def room():
    room_path=["1","2"]
    user_choice = ""

print ("If you decide to ditch Todd and go to the campfire alone, enter 1")
print ("If you decide to drag Todd with you to the campfire, enter 2")
user_choice = input("your option number")

if user_choice == room_path [1]:
    print ("yes")
elif user_choice == room_path [2]:
    print ("no")

当我运行代码并输入一个数字时,这是我得到的错误:

    if user_choice == room_path [1]:
NameError: name 'room_path' is not defined

标签: pythonpython-3.xnameerror

解决方案


发生错误是因为名称room_path是在函数范围内声明的 room,因此无法从该函数外部调用。

这是一个很好的链接,解释了 Python 中变量的范围:

http://python-textbok.readthedocs.io/en/1.0/Variables_and_Scope.html

要解决此问题,您可以在函数room_path之外声明room,您可能还想使用user_choice并完全删除该room函数。

您的代码将如下所示:

room_path=["1","2"]
user_choice = ""

print ("If you decide to ditch Todd and go to the campfire alone, enter 1")
print ("If you decide to drag Todd with you to the campfire, enter 2")
user_choice = input("your option number")

if user_choice == room_path [1]:
    print ("yes")
elif user_choice == room_path [2]:
    print ("no")

推荐阅读