Why does Python complain about reference before as

2020-07-22 17:44发布

问题:

Why does Python complain about chrome being referenced before assignment? It does not complain about the dictionary. This is with Python 2.5 if it makes a difference.

def f():
  google['browser'] = 'chrome'
  chrome += 1

google = dict()
chrome = 1
f()

I can make it work with global chrome of course, but I'd like to know why Python does't consider the variable to be assigned. Thanks.

回答1:

It's out of scope: read here



回答2:

In the statement

chrome += 1

and it has not been created yet. The variables are created the first time they are assigned. In this case, when python sees the code incrementing 'chrome', it doesn't see this variable at all.

Try rearranging your code as

chrome = 1

def f():
  global chrome
  google['browser'] = 'chrome'
  chrome += 1

google = dict()
f()