2013-04-18 89 views
1

嗨我有問題寫這個簡單的程序。我剛剛開始使用Python,希望得到一些幫助。當我在程序底部運行start()函數時,一切正常,直到第一個raw_input()之後。例如,如果用戶輸入「get coffee」,則會打印字符串「Fair enough take a break」,但在此之後,不是像我想的那樣運行coffee()函數,而是再次循環到start()函數。我的簡單代碼在這裏有什麼問題?

有人能幫忙嗎? 非常感謝。

def engine(next_scene): 
    scenes = {"start":start(),"coffee":coffee(),"work":work()} 
    return scenes[next_scene] 

def start(): 
    print "you are in the office" 
    print "you wonder what to do" 
    action = raw_input("what do you do? Get coffee or work?") 

    if action == "get coffee": 
     print "Fair enough take a break" 
     next_scene = "coffee" 
     engine(next_scene) 
    if action == "work": 
     print "Good man, you are well on your way to being a coder" 
     next_scene = "work" 
     engine(next_scene) 

def coffee(): 
    print "You walk out of the room" 
    print "You head down the stairs and into the cafe" 
    print "You order an espresso" 
    print "You neck it down" 
    print "Yumm" 
    print "You are wired" 
    action = raw_input("Now what? Work or go home? > ") 

    if action == "work": 
     print "You head back upstairs" 
     next_scene = "work" 
     engine(next_scene) 
    if action == "go home": 
     print "You lazy git" 

def work(): 
    print "You beaver away and become a cool coder" 
    next_scene = "start" 
    engine(next_scene) 

start() 
+0

我想你想在場景字典中刪除函數後的'()'。包括括號試圖調用這些函數。 – BlackVegetable

回答

4

scenes = {"start":start(),"coffee":coffee(),"work":work()} 

應該

scenes = {"start":start,"coffee":coffee,"work":work} 

你叫字典中的定義的功能,但你想要得到的函數對象。

+3

而OP可能想要將以下行更改爲:'return scenes [next_scene]()' –

+1

當然可以。而且他必須注意,他不會將呼叫堆疊到'engine'上。 – Matthias

+0

@ Mathias.Thanks for your help.Sorry,但我怎麼去實際調用函數coffee(),然後在事件next_scene =「coffee」?對於基本問題抱歉。 – Reno

1

您的引擎功能應該喜歡。

def engine(next_scene): 
    scenes = {"start":start,"coffee":coffee,"work":work} 
    scenes[next_scene]() 
相關問題