简体   繁体   中英

Declare variable to function without running it

def user(choose):
    if (choose == "1"):
        play = game()
    elif (choose == "2"):
        return stats(play)
    else:
        return quit()

I want to take the value from function game() and use it in stats(), but I get an error saying that play is not defined. How do I declare game() and use it in another function?

You could "postpone" execution of func1 :

def func1():
    return 'abc'

def something_else(callable):
    callable()

def main():
    hello = None

    def f():
        """set result of func1 to variable hello"""
        nonlocal hello
        hello = func1()

    # over here func1 is not executed yet, hello have not got its value
    # you could pass function f to some other code and when it is executed, 
    # it would set result for hello 
    print(str(hello))  # would print "None"
    call_something_else(f)
    print(str(hello))  # would print "abc"

main()

After question has changed...

Right now, your local variable play is out of scope for stats. Also, looks like you expect that function would be called twice. You need to save play in global content

play = None  # let's set it to some default value
def user(choose):
    global play  # let python know, that it is not local variable

    if choose == "1":  # no need for extra brackets
        play = game()

    if choose == "2" and play:  # double check that play is set
        return stats(play)

    return quit()

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