global variables - UnboundLocalError in Python -


this question has answer here:

what doing wrong here?

counter = 0  def increment():   counter += 1  increment() 

the above code throws unboundlocalerror.

python doesn't have variable declarations, has figure out scope of variables itself. simple rule: if there assignment variable inside function, variable considered local.[1] thus, line

counter += 1 

implicitly makes counter local increment(). trying execute line, though, try read value of local variable counter before assigned, resulting in unboundlocalerror.[2]

if counter global variable, global keyword help. if increment() local function , counter local variable, can use nonlocal in python 3.x.


Comments

Popular posts from this blog

ios - RestKit 0.20 — CoreData: error: Failed to call designated initializer on NSManagedObject class (again) -

java - Digest auth with Spring Security using javaconfig -

laravel - PDOException in Connector.php line 55: SQLSTATE[HY000] [1045] Access denied for user 'root'@'localhost' (using password: YES) -