Why does Python complain about the link before assignment when incrementing variables in a function?

Why chromedoes Python complain about the link before the assignment? He does not complain about the dictionary. This is with Python 2.5, if that matters.

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

google = dict()
chrome = 1
f()

I can make it work with global chrome, of course, but I would like to know why Python is not considering this variable. Thank.

+3
source share
2 answers

This is out of scope: read here

-1
source

In a statement

chrome += 1

and it is not created yet. Variables are created upon first assignment. In this case, when python sees the code incrementing "chrome", it does not see this variable at all.

chrome = 1

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

google = dict()
f()
+5

Source: https://habr.com/ru/post/1771647/


All Articles