0

大约 2 周前,我刚刚开始学习 Python 3。我决定制作一个基本的文本游戏 但是,我在代码中遇到了一个我似乎无法修复的错误,而且我在其他任何地方都找不到。当我运行我的游戏(代码传入)时,我收到此错误:

Welcome to the room. This is the room in which this game takes place

Press enter to continue.

What would you like to do? Type HELP for your options

HELP

Traceback (most recent call last):


File "C:/Users/Michael/Desktop/mess.py", line 35, in <module>
inputFunc()


File "C:/Users/Michael/Desktop/mess.py", line 7, in inputFunc
inputExam()


File "C:/Users/Michael/Desktop/mess.py", line 9, in inputExam
if (inSet == "LOOK"):

NameError: global name 'inSet' is not defined

这是我的游戏的代码:

# functions:
def youLose():
    print("You lost.")
def inputFunc():
    print("What would you like to do? Type HELP for your options")
    inSet = input()
    inputExam()
def inputExam():
    if (inSet == "LOOK"):
        print("You are in a room. There is a door in front of you. You have a key in your hand. There is a slip of paper on the ground.")
        inputFunc()
    elif (inSet == "HELP"):
        print("Use LOOK to examine your surroundings. Use OPEN to open things. Use EXAMINE to examine things. Use QUIT to quit the game. Remember to use ALL CAPS so the processor can understand you")
        inputFunc()
    elif (inSet == "EXAMINE PAPER"):
        print("The paper reads: 'There is only one winning move'")
        inputFunc()
    elif (inSet == "OPEN DOOR"):
        print("You open the door using your key. There is a bright light on the other side, blinding you. You feel a familiar feeling as you realize that you have died.")
        input("Press enter to continue.")
        youLose()
    elif (inSet == "EXAMINE DOOR"):
        print("A simple oaken door.")
        inputFunc()
    elif (inSet == "QUIT"):
        print("You hear a clicking of gears. You realize that the only winning move is not to play. You Win!")
    elif (inSet == "EXAMINE KEY"):
        print("A small, brass key that looks to fit the lock on the door.")
        inputFunc()
    else:
        print("Syntax Error")
# base:
print("Welcome to the room. This is the room in which this game takes place")
input("Press enter to continue.")
inputFunc()
4

1 回答 1

1

您的问题是变量范围:

def inputFunc():
    print("What would you like to do? Type HELP for your options")
    inSet = input()
    inputExam()

def inputExam():
    if (inSet == "LOOK"):
        ...

inSet中定义inputFunc。它在 之外不存在inputFunc,因此您不能在 中使用它inputExam

您可以将其设为全局:

inSet = ''

def inputFunc():
    global inSet

    print("What would you like to do? Type HELP for your options")
    inSet = input()
    inputExam()

def inputExam():
    global inSet

    if (inSet == "LOOK"):
        ...

或将其作为参数传递给inputExam

def inputFunc():
    print("What would you like to do? Type HELP for your options")
    inSet = input()
    inputExam(inSet)

def inputExam(inSet):
    if (inSet == "LOOK"):
        ...

我会选择后者。

于 2013-05-11T18:35:20.010 回答