简体   繁体   中英

How do I make a function to accept an argument that is another function?

My question might seem confusing but it is the only way I could think of wording it. I apologise for any confusion, I will try my best to explain.

Basically what I am trying to do is have a simple exit function within my game that asks "Do you want to exit?" If the user inputs no it returns them back to a function they were in.

Here is what I have tried to do however it seems to just be looping back to the 'bear_room()' function.

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()

You almost got it; you just need to not call bear_room when you're passing it as an argument:

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

Conversely, you need to call stage as a function:

    elif con_ext == 'no':
        stage()

You need to understand the difference between passing a function around and calling it.

Here you are copying a reference to the function raw_input into the variable next , without actually executing it. You probably want to add parentheses () to raw_input :

next = raw_input

Here you are calling bear_room() again, recursively, instead of passing a reference to it to the exit_game function. You probably want to remove the parentheses () to bear_room :

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

Again, mentioning a function without parentheses does not execute it, so you want to add those here too:

elif con_ext == 'no':
    stage

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM