首页 > 解决方案 > Python3变量传递问题

问题描述

示例代码,尽量忽略它看起来不必要地过于复杂 - 这是从实际代码中简化的方式,但准确地模仿了流程。

def setup():
   print("Setting up...")
   do_something()

def do_something():
   task = str(input("Enter a task to do: "))
   try:
      print("Doing {}...".format(task))
   except:
      print("Failed to do {}...".format(task))
   finally:
      return task

def choose_2(choice):
   print("You chose {}".format(choice))

def menu_1():
   choice = int(input("Choose 1 or 2: "))
   if choice == 1:
      setup()
      menu_2(task)

menu_1()

然而,程序返回“ UnboundLocalError: local variable 'task' referenced before assignment

为什么do_something() 将变量返回taskif语句中menu_1()?一旦setup()(以及随后do_something())完成运行,do_something()返回值不应该保留在if语句中,因为它还没有完成吗?

标签: pythonpython-3.xvariablesreturntry-catch

解决方案


流程是: menu_1() => menu_2(task)

task没有在范围内定义,menu_1()所以无法定义。

您可能打算这样做:

def setup():
   print("Setting up...")
   return do_something()
.....
# in menu_1():
menu_2(setup())

请注意,因为setup现在 RETURNS 某些东西,所以它可以使用该返回值。


推荐阅读