Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python - How to reference a global variable from a function [duplicate]

Tags:

python

scope

I must be missing some very basic concept about Python's variable's scopes, but I couldn't figure out what.

I'm writing a simple script in which I would like to access a variable that is declared outside the scope of the function :

counter = 0

def howManyTimesAmICalled():
    counter += 1
    print(counter)

howManyTimesAmICalled()

Unexpectedly for me, when running I get :

UnboundLocalError: local variable 'counter' referenced before assignment

Adding a global declaration at the first line

global counter
def howManyTimesAmICalled():
    counter += 1
    print(counter)

howManyTimesAmICalled() 

did not change the error message.

What am I doing wrong? What is the right way to do it?

Thanks!

like image 654
Ohad Dan Avatar asked May 30 '26 04:05

Ohad Dan


1 Answers

You need to add global counter inside the function definition. (Not in the first line of your code)

Your code should be

counter = 0

def howManyTimesAmICalled():
    global counter
    counter += 1
    print(counter)

howManyTimesAmICalled()
like image 83
Sukrit Kalra Avatar answered May 31 '26 19:05

Sukrit Kalra



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!