首页 > 解决方案 > Python全局变量int和set在函数中访问时结果不同

问题描述

text = "abcdefg"
counter = 0
chars = set()
def do_something(i):
    print(chars)
    print(counter)
    counter += 1
    if i not in chars:
        chars.add(i)

for i in text:
    do_something(i)

运行错误:

UnboundLocalError: local variable 'counter' referenced before assignment

在计数器之前添加全局时,它运行良好

set()
0
{'a'}
1
{'a', 'b'}
2
{'c', 'a', 'b'}
3
{'c', 'a', 'd', 'b'}
4
{'a', 'b', 'c', 'e', 'd'}
5
{'a', 'f', 'b', 'c', 'e', 'd'}
6

为什么 int 变量“ counter ”在函数内部调用时需要声明为全局变量?
为什么在函数内部调用时可以在没有全局声明的情况下使用set chars ?

标签: pythonfunctionglobal

解决方案


推荐阅读