gwydion93
gwydion93

Reputation: 1923

Function to add to a counter throws local variable error

I am trying to make a function that adds to a simple variable counter.

counter = 0

If I just do it like this, I get the following error:

 def counter_adder(rank):
      if rank < 5:
           counter = counter + 1

UnboundLocalError: local variable 'in_in' referenced before assignment

I can make it work by adding a global variable within the function:

 def counter_adder(rank):
      global counter
      if rank < 5:
           counter = counter + 1

However, I've heard this is bad (why?) and wanted to know if there was a better way to do this?

Upvotes: 0

Views: 35

Answers (1)

Dschoni
Dschoni

Reputation: 3872

I just found out recently, that you can attach attributes to functions. This would be the exact use-case for something like that.

def counter_adder(rank):
  if rank < 5:
    counter_adder.counter+=1

counter_adder.counter = 0

counter_adder(5)

print(counter_adder.counter)

Upvotes: 1

Related Questions