3

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!

4

1 回答 1

8

您需要global counter在函数定义中添加。(不在代码的第一行)

你的代码应该是

counter = 0

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

howManyTimesAmICalled()
于 2013-07-29T16:06:27.200 回答