开发者

Why does Python complain about reference before assignment when increasing variables in a function?

开发者 https://www.devze.com 2023-01-21 09:01 出处:网络
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.

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()
ch开发者_开发技巧rome = 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.


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()


It's out of scope: read here

0

精彩评论

暂无评论...
验证码 换一张
取 消