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)
run with error:
UnboundLocalError: local variable 'counter' referenced before assignment
When add global before counter, it runs well
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
Why does the int variable "counter" need to be declared as global when called inside a function?
Why can set chars be used without a global declaration when called inside a function?