获取“名称错误:未定义名称‘房间路径’”

2024-09-29 00:16:09 发布

您现在位置:Python中文网/ 问答频道 /正文

这是我遇到问题的代码。我使用的是python3.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")

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

^{pr2}$

Tags: thetopath代码youifdefroom
3条回答

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

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

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

要解决这个问题,您可以在room函数之外声明room_path,这可能还需要对user_choice进行声明,并完全删除{}函数。在

你的代码看起来像这样:

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

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

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

我觉得有点问题

room_path=["1","2"]

它为room_path列表定义str

但是当您输入str是:1或{}应该匹配

^{pr2}$

with [0]room_path列表的第一列。在

相关问题 更多 >