2013-05-11 122 views
0

大約兩週前我剛開始學習Python 3。我決定做一個基本的文本遊戲然而,我遇到了代碼中的一個錯誤,我似乎無法修復,而且我找不到其他任何地方。當我運行我的遊戲(代碼傳入),我得到這個錯誤:Python 3:未定義全局名'inSet'

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

回答

1

你的問題是變量的作用域:

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

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

inputFunc中定義了inSet。它不存在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"): 
     ... 

我將與後者去。