gpt4 book ai didi

Python 错误 : local variable referenced before assignment

转载 作者:行者123 更新时间:2023-12-02 10:49:27 25 4
gpt4 key购买 nike

这是我的代码:

import time

GLO = time.time()

def Test():
print GLO
temp = time.time();
print temp
GLO = temp

Test()

Traceback (most recent call last): File "test.py", line 11, in Test() File "test.py", line 6, in Test print GLO UnboundLocalError: local variable 'GLO' referenced before assignment

在添加GLO = temp时出现错误,如果我注释掉,函数可以执行成功,为什么?

如何设置 GLO = temp

最佳答案

在测试方法中指定您要引用全局声明的 GLO 变量,如下所示

def Test():
global GLO #tell python that you are refering to the global variable GLO declared earlier.
print GLO
temp = time.time();
print temp
GLO = temp

可以在这里找到类似的问题: Using a global variable within a method

关于Python 错误 : local variable referenced before assignment,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17641431/

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