[英]How do I make a function to accept an argument that is another function?
我的問題似乎令人困惑,但這是我想到的唯一方法。 對於任何混亂,我深表歉意,我將盡力解釋。
基本上,我想做的是在游戲中提供一個簡單的退出功能,詢問“您要退出嗎?”。 如果用戶輸入否,則將其返回到其所在的功能。
這是我嘗試執行的操作,但是似乎只是循環回到“ bear_room()”函數。
def bear_room():
print "You are greeted by a bear"
next = raw_input()
if next == 'fight':
print 'You tried to fight a bear. You died'
elif next == 'exit':
exit_game(bear_room())
else:
print 'I did not understand that!'
bear_room()
def exit_game(stage):
print '\033[31m Are you sure you want to exit? \033[0m'
con_ext = raw_input(">")
if con_ext == 'yes':
exit()
elif con_ext == 'no':
stage
else:
print 'Please type ''yes'' or ''no'
exit_game()
你幾乎明白了; 您只需在將其作為參數傳遞時不調用bear_room
:
elif next == 'exit':
exit_game(bear_room)
相反,您需要將stage
作為函數調用:
elif con_ext == 'no':
stage()
您需要了解傳遞函數和調用函數之間的區別。
在這里,您將對raw_input
函數的引用復制到next
變量中,而無需實際執行它。 您可能要在raw_input
添加括號()
:
next = raw_input
在這里,您將遞歸地再次調用bear_room()
,而不是exit_game
它的引用傳遞給exit_game
函數。 您可能要刪除括號()
到bear_room
:
elif next == 'exit':
exit_game(bear_room())
同樣,提及不帶括號的函數不會執行該函數,因此您也想在此處添加這些函數:
elif con_ext == 'no':
stage
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.