def user(choose):
if (choose == "1"):
play = game()
elif (choose == "2"):
return stats(play)
else:
return quit()
我想从game()函数中获取值并在stats()中使用它,但是我收到一条错误消息,说未定义游戏。如何声明game()并在其他函数中使用它?
答案 0 :(得分:1)
您可以“推迟”执行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()
问题改变之后...
现在,您的本地变量play
超出了统计范围。
此外,看起来您希望该函数将被调用两次。
您需要在全局内容中保存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()