2014-11-02 3 views
-1

작은 텍스트 모험을 만들고 싶었습니다.파이썬 : 글로벌 이름 '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

+0

고마워, 나는 지금했다. –

+0

최소한의 예는 아닙니다. 이 기사를 다시 읽으십시오 - 우리는 무의미한 뭉치 (당신이 게시 한 내용 대부분이 관련성이없고 문제를 재현하기에 불충분 함)없이 예제를 사용하여 문제를 재현 할 수 있어야합니다. – jonrsharpe

답변

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

오, 나는 이것이 그렇게 단순하다고 생각하지 않았을 것입니다. 빠른 답변을 해주시고 저에게 더 좋은 아이디어를 주신 것에 대해 감사드립니다! –

관련 문제