如何让函数接受另一个函数的参数?

问题描述:

我的问题似乎令人困惑,但它是我想到措辞的唯一方法。我对任何混淆抱歉,我会尽我所能解释。如何让函数接受另一个函数的参数?

基本上,我试图做的是有我的游戏,要求中一个简单的exit函数“你想退出吗?”如果用户输入没有返回他们回到他们在。

这里的功能是什么,我试图做不过它似乎只是循环回“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() 
+0

只是一个旁白:命名一个变量'next'会影响内置'next' - 所以你不妨考虑改变名字 - 例如'next_room' ... – 2013-03-17 15:47:51

你差不多了;你只需要不叫bear_room当你将它作为一个参数:

elif next == 'exit': 
     exit_game(bear_room) 

相反,你需要调用stage作为一个功能:

elif con_ext == 'no': 
     stage() 
+0

工作很好!谢谢! – George 2013-03-17 15:46:08

你需要了解的传球之间的区别围绕并调用它的函数。

此处您正在将对函数raw_input的引用复制到变量next中,而没有实际执行它。你可能想圆括号()raw_input

next = raw_input 

这里你再次调用bear_room(),递归,而不是传递一个参考,以它为exit_game功能。你可能想删除括号()bear_room

elif next == 'exit': 
    exit_game(bear_room()) 

再次,提功能,不带括号不执行,所以要添加那些在这里太:

elif con_ext == 'no': 
    stage