获取“NameError:name'house_path'未定义”

时间:2018-05-27 23:47:54

标签: python python-3.x nameerror

以下是我遇到问题的代码。我正在使用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

3 个答案:

答案 0 :(得分:1)

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

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

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

要解决此问题,您可以在room_path函数之外声明room,您可能还想对user_choice进行操作,并完全删除room函数。< / p>

您的代码看起来像这样:

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")

答案 1 :(得分:0)

我认为有点问题,

room_path=["1","2"]

str列表

定义room_path

但输入str时:12应匹配

if user_choice == room_path [0]:
带有[0]

room_path列表的第一列。

答案 2 :(得分:0)

发生错误是因为您在方法和访问中定义了oxml变量,并在方法之外使用了room_path变量。

room_path