python - 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()
不将变量返回task
到if
语句中menu_1()
?一旦setup()
(以及随后do_something()
)完成运行,do_something()
返回值不应该保留在if
语句中,因为它还没有完成吗?
解决方案
流程是:
menu_1() => menu_2(task)
task
没有在范围内定义,menu_1()
所以无法定义。
您可能打算这样做:
def setup():
print("Setting up...")
return do_something()
.....
# in menu_1():
menu_2(setup())
请注意,因为setup
现在 RETURNS 某些东西,所以它可以使用该返回值。
推荐阅读
- sql-server - 多个数据源的 Spring Boot 问题
- jquery - 在将图像获取为 encode64 时删除 encode64 标头数据。?
- r - 如何找到不同年龄组的信用卡持有人百分比
- firebase - 如何在应用程序的二进制文件中捆绑默认的 ML 人脸模型?
- android - 使用 webview 在 Chrome 73 android 中取消对所有字体的请求
- dart - 如何使用for循环将具有相同名称的元素添加到列表中
- r - 我想要在包含使用 R 的文本的列中的第一个句号之后的单词
- mysql - 如何添加具有不同时区的额外列
- design-patterns - 哪种设计模式解决了多规则检查?
- java - 从头开始为 JRE 创建 Docker 映像