I made the two functions below in Python 3. The first function test_list
works fine with the list a
without error. I can modify the list element in that function.
However, the second funciton test_int
will pop an error local variable 'b' referenced before assignment
. Why can't I do this to the variable b
?
a=[1,2,3]
def test_list():
a[0]=2
return a
b = 2
def test_int():
b = 1
return b
CodePudding user response:
b = 1
is equivalent to b = b.__iadd__(1)
; since the name b
gets bound by that statement (l.h.s.), the compiler infers that b
is a local variable; however, the r.h.s. expression contains the name b
as well and thus you get the error "local variable 'b'
referenced before assignment" (the local name b
doesn't refer to anything at the time when the expression is evaluated).
a[0] = 2
on the other hand is equivalent to a.__setitem__(0, 2)
and thus involves no name binding.
If you wish to modify a global name binding within a function, you can use the keyword global
; there's also the equivalent nonlocal
for names contained in an outer, but not the global, scope.
CodePudding user response:
b
is globally scoped. You are attempting to modify it in a local context, ie in test_int
. You need the global
keyword if you wish to modify a globally scoped variable in a local context. Read about variable scoping in python here.
The reason the first function test_list
works is because you are not modifying the global variable itself, but only the contents. Here's a good explanation of what happens when you modify global variables: https://stackoverflow.com/a/31437415/14715054
This will fix your problem:
a=[1,2,3]
def test_list():
a[0]=2
return a
b = 2
def test_int():
global b
b = 1
return b