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
Post a Comment