Function - Unexpected behavior of Python39s variable scope

De openkb
Aller à : Navigation, rechercher

Sommaire

Questions

   This question already has an answer here:
    * /questions/9264763/unboundlocalerror-in-python /questions/9264763/unboundlocalerror-in-python 8 answers

Answers

It s because when you do some operation on a (which is expected to be global) python treats it like local.

So when you do a+=1 it searches for local variable and it doesn t find s any and hence the error.

If you trying to increment the global a then you need to mention a with a global keyword before that. Else use some other variable and increment it

http://stackoverflow.com/questions/21456739/unboundlocalerror-local-variable-l-referenced-before-assignment-python http://stackoverflow.com/questions/21456739/unboundlocalerror-local-variable-l-referenced-before-assignment-python

Consider this

c = 0

def increment():
  print c
  c += 1

increment()

if there is an assignment to a variable inside a function, that variable is considered local Thus, the line

c += 1

implicitly makes counter local to increment(). So print c will search for local variable c rather than global variable c I hope that s fine now

Source

License : cc by-sa 3.0

http://stackoverflow.com/questions/30522721/unexpected-behavior-of-pythons-variable-scope

Related

Outils personnels
Espaces de noms

Variantes
Actions
Navigation
Outils