2014-11-02 123 views
-1

我想創建一個小型文本冒險。Python:未定義全局名稱'xxx'

You can go to an old school and have the option to go inside by damaging an old door or by finding an open window. There is a dog in the basement and if you take the door, he wakes up because of the noise and kills you instantly when you go into the basement. But if you go through the window, he should be asleep when you enter the basement and wake up then.

如果他已經醒了(school_dogawake = True),那麼一切都很正常,但如果他沒有,school_dogawakeFalse,應在地下室設置爲True,但產生一個錯誤:NameError: global name 'school_dogawake' is not defined(它是全球性的) 。

def initialize(): 
    school_dogawake = False 
    school() 

def school(): 
    global school_dogawake 
    choice = raw_input("How to enter the school? ") 
    if choice == 'break door': 
     school_dogawake = True 
     school_floor() 
    elif choice == 'window': 
     school_floor() 

def school_floor(): 
    global school_dogawake 

    if school_dogawake: # this works! 
     print school_dogawake # prints True 
     print "The dog was awake." 
    else: # global name 'school_dogawake' is not defined 
     print "The dog is waking up." 
     school_dogawake = True 

initialize() 
+0

將代碼*的[最小示例](http://stackoverflow.com/help/mcve)中的問題*。 – jonrsharpe 2014-11-02 09:06:56

+0

謝謝,我現在做了。 – 2014-11-02 09:10:40

+0

這不是一個簡單的例子。請重新閱讀那篇文章 - 我們應該能夠使用該示例重新創建問題,而不會有任何不相干的垃圾(大部分內容都是無關緊要的,並且不足以重現問題)。 – jonrsharpe 2014-11-02 09:12:01

回答

0

你缺少initialize一個global,因此初始

school_dogawake = False 

局部的功能。這是簡單的修復:

def initialize(): 
    global school_dogawake 
    school_dogawake = False 
    school() 

但是,global通常是一個壞主意。考慮代替繞過一個state詞典:

def initialize(): 
    state = {'dog awake': False} # set initial state 
    school(state) 

def school(state): 
    ... 
    state['dog awake'] = 'True' # update state as required 
    ... 
    school_floor(state) 

def school_floor(state): 
    if state['dog awake']: # test current state 
     ... 
+0

哦,我從來沒有想過這很簡單。感謝您的快速回答,併爲我提供更好的主意! – 2014-11-02 09:29:29