gpt4 book ai didi

python - 赋值前引用的局部变量。 Python

转载 作者:太空宇宙 更新时间:2023-11-04 02:21:40 24 4
gpt4 key购买 nike

我写了下面的函数:

def get_running_time(test):
for line in PERFORMANCE_FILE:
print(test_time)
line_rr = line.split()
test_time = int(line_rr[-2])
print(test_time)
return test_time

我得到了错误:

"local variable 'test_time' referenced before assignment"

我看到所有的解决方案都依赖全局变量,但我不想使用它。我尝试使用全局变量,但它让我的事情变得更复杂,因为当我调用函数“获取运行时间”时,它不会在开始时考虑“test_time”的初始化,并且全局在整个运行过程中保持相同的数字程序。 还有另一种方法可以解决这个问题吗?谢谢。

最佳答案

UnboundLocalError 是因为迭代器 PERFOMANCE_FILE 可能为空,在这种情况下,for 的迭代永远不会发生,在这种情况下 test_time 永远不会被设置(因为它只在循环内设置)。

但是当您返回 test_time 时,将引发 UnboundLocalError。您可以改为在顶部设置默认值以在 PERFOMANCE_FILE 为空时返回:

def get_running_time(test):
test_time = '' # Default
for line in PERFORMANCE_FILE:
print(test_time)
line_rr = line.split()
test_time = int(line_rr[-2])
print(test_time)
return test_time

关于python - 赋值前引用的局部变量。 Python,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51466556/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com