0
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?

nick
  • 1
  • This has **nothing to do with types**. An assignment statement *anywhere* in a function, here `counter += 1` makes that variable **local**. If you want to assign to a global variable in a local scope you must use `global` – juanpa.arrivillaga Jul 30 '21 at 03:25
  • 2
    They don't have different rules, you are using the differently. `chars` isn't be reassigned, but `counter` is, which makes it local. – Loocid Jul 30 '21 at 03:26
  • This is an important distinction. With `chars`, you are changing the object (by adding to the set), but it's still the same object throughout. With `counter`, you are binding the name to a different object. That's what makes the `global` required. – Tim Roberts Jul 30 '21 at 03:28

0 Answers0