The following code works as expected in both Python 2.5 and 3.0:
a, b, c = (1, 2, 3) print(a, b, c) def test(): print(a) print(b) print(c) # (A) #c+=1 # (B) test()
However, when I uncomment line (B), I get an
UnboundLocalError: "c" not assigned at line (A). The values of
b are printed correctly. This has me completely baffled for two reasons:
Why is there a runtime error thrown at line (A) because of a later statement on line (B)?
Why are variables
b printed as expected, while
c raises an error?
The only explanation I can come up with is that a local variable
c is created by the assignment
c+=1, which takes precedent over the "global" variable
c even before the local variable is created. Of course, it doesn"t make sense for a variable to "steal" scope before it exists.
Could someone please explain this behavior?
Python treats variables in functions differently depending on whether you assign values to them from inside or outside the function. If a variable is assigned within a function, it is treated by default as a local variable. Therefore, when you uncomment the line you are trying to reference the local variable
c before any value has been assigned to it.
If you want the variable
c to refer to the global
c = 3 assigned before the function, put
as the first line of the function.
As for python 3, there is now
that you can use to refer to the nearest enclosing function scope that has a
Python Workout isn’t designed to teach you Python, although I hope and expect that you’ll learn quite a bit along the way. It is meant to help you improve your understand- ing of Python and how to...
It’s in all of us. Data science is what makes us humans what we are today. No, not the computer-driven da...
Mark Lutz is the global leader in Python training, author of the oldest and best-selling Python texts, and a pioneer in the Python community since 1992.
Mark Lutz is the author of the found...
The Pragmatic Programmer: Your Journey To Mastery, 20th Anniversary Edition (2nd Edition). The Pragmatic Programmer is one of those rare technical books that you will read, reread, and re-read over...