简体   繁体   English

声明变量运行而不运行

[英]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. 我想从game()函数中获取值并在stats()中使用它,但是我收到一条错误消息,说未定义游戏。 How do I declare game() and use it in another function? 如何声明game()并在另一个函数中使用它?

You could "postpone" execution of func1 : 您可以“推迟”执行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. 现在,您的本地变量play超出了统计范围。 Also, looks like you expect that function would be called twice. 此外,看起来您希望该函数将被调用两次。 You need to save play in global content 您需要将play内容保存在全局内容中

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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