Python:如何使用函数递增全局变量

标签 python python-3.x

<分区>

counter = 0

def addCounter():
    counter = counter + 1
    return counter

UnboundLocalError: local variable 'counter' referenced before assignment.

每次运行此函数时,我都会尝试进行计数器计数。我也尝试过将计数器变量作为参数传递,但这也不起作用。

最佳答案

你需要:

counter = 0

def addCounter():
     global counter
     counter = counter + 1
     return counter

说明:在 Python 中,内部变量的声明是隐式的,赋值会自动声明左侧的值,但是该声明始终在局部范围内。这就是为什么如果你这样写:

counter = 0
def addCounter():
    return counter

它会工作正常,但只要你添加一个作业

counter = 0
def addCounter():
    counter += 1
    return counter

它中断了:赋值添加了一个隐式本地声明。 global 覆盖了这个,虽然它要求全局变量事先存在,但它不会创建一个全局变量,它只是告诉函数这是一个全局变量,它可以重新分配给它。

I've tried passing the counter variable in as a parameter as well, but that doesn't work either.

确实不是。 Python 的求值策略有时被称为“共享传递”(或“按值传递引用”),从技术上讲是“按值传递”,但这个术语有点令人困惑,因为在这种情况下,值是引用,引用被复制,但引用的对象不是,因此最终行为与“按值传递”预期的正常预期不同。

关于Python:如何使用函数递增全局变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59836887/

相关文章:

python - 将包含元组列表的字典转换为列表

python - 如何使用一个键将多个列表值的数据框制作成python中的字典?

python - 使用 pytest 和假设进行异常处理和测试

python - 在Python中同时对URL发出多个POST请求

python - 使用 Streamlit file_uploader 后 "TypeError: expected str, bytes or os.PathLike object, not NoneType"

python - 删除DataFrame中 "/"之前的空白区域

python - 如何提高 python 中的合并排序速度

python - 用 @s :eng only on lines starting with *CHI: 标记文本文件中的所有英文单词

python - 基于外键的 Django 选择

python - 如何从 Python 中的十六进制字符串中删除 '\x'?