Python变量未定义错误

时间:2018-03-27 17:47:21

标签: python

我认为制作基于文本的冒险游戏会很酷。我在这段代码中遇到命名错误的问题:

 elif room1_choice1=='Search the room':
        print('You have chosen to search the room')
        print("As you walk around the room you find a chest that you couldn't see from the doorway")
        print('You see only two choices, to attempt to open it or to search the rest of the room')
        print("Type 'Attempt to open' to try to open the chest or type 'Keep searching' to continue your search")
        room1_chestChoice=input(':')
 if room1_chestChoice=='Attempt to open':
        print('You heave at the lid with all your strength but fail to open it.')
        print('It looks like it is locked and you need a key')
        print("Type 'Keep searching' to try and find the key")
        room1_chestChoice=input(':')

我在中间的if收到错误:

Traceback (most recent call last):
  File "C:/Users/maxim/PycharmProjects/APCSP project/Prototype 1.py", line 41, in <module>
    if room1_chestChoice=='Attempt to open':
NameError: name 'room1_chestChoice' is not defined

有人可以帮忙吗?

1 个答案:

答案 0 :(得分:2)

room1_chestChoice仅定义 ,前一个选项room1_choice1是&#34;搜索房间&#34;。仅在这种情况下检查room1_chestChoice才有意义。更改缩进以反映您的决策树:

elif room1_choice1=='Search the room':
    print('You have chosen to search the room')
    ...
    room1_chestChoice=input(':')
    if room1_chestChoice=='Attempt to open':
         print('You heave at the lid
               ...
         room1_chestChoice=input(':')

第二个if必须完全位于依赖于elif的代码中。