我想創建一個小型文本冒險。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_dogawake
是False
,應在地下室設置爲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()
將代碼*的[最小示例](http://stackoverflow.com/help/mcve)中的問題*。 – jonrsharpe 2014-11-02 09:06:56
謝謝,我現在做了。 – 2014-11-02 09:10:40
這不是一個簡單的例子。請重新閱讀那篇文章 - 我們應該能夠使用該示例重新創建問題,而不會有任何不相干的垃圾(大部分內容都是無關緊要的,並且不足以重現問題)。 – jonrsharpe 2014-11-02 09:12:01