2013-08-24 103 views
1

我想從學習python的困難方式做一個練習,我卡在某物上。我創建了一個函數,如果其中一個語句被滿足,我想把它放在另一個函數中。這是我如何試圖做到這一點大綱:Python調用函數

def room_1(): 
    print "Room 1" 
    button_push = False 

    while True: 
     next = raw_input("> ") 

     if next == "1": 
      print "You hear a click but nothing seems to happen." 
      button_push = True 

     elif next == "2": 
      print "You enter room 2" 
      room_2() 

def room_2(): 
    print "Room 2" 

    while True: 
     next =raw_input("> ") 

     if next == "1" and button_push: 
      print "You can enter Room 3" 
      room_3() 

如果button_push得到滿足,那麼我會希望看到,在room_2。任何人都可以幫助我嗎?

回答

1

您可以通過button_push作爲參數傳遞給下一個房間:

def room_1(): 
    print "Room 1" 
    button_push = False 

    while True: 
     next = raw_input("> ") 

     if next == "1": 
      print "You hear a click but nothing seems to happen." 
      button_push = True 

     elif next == "2": 
      print "You enter room 2" 
      room_2(button_push) # pass button_push as argument 

def room_2(button_push): # Accept button_push as argument 
    print "Room 2" 

    while True: 
     next =raw_input("> ") 

     if next == "1" and button_push: # button_push is now visible from this scope 
      print "You can enter Room 3" 
      room_3() 
+0

感謝您的及時回覆!只有在我輸入「1」和「2」之後,纔有辦法傳遞button_push? – rolandvarga

+0

@ user2714517如果你輸入了'1',然後輸入'2'或'False',那麼你傳遞'True'。如果你需要知道'1',然後'2'被按下,你可以檢查'button_push'的值。既然你有'和button_push',如果他們輸入'1'然後輸入'2',你將只進入房間3。 –

+0

完美的作品!非常感謝! :) – rolandvarga