+ 2
What's wrong with the variable ?
a = [1, 2, 3] a += [4] print(a) # [1, 2, 3, 4] b = [1, 2, 3] def add(n): print(b) # [1, 2, 3] b += [n] add(4) # UnboundLocalError: local variable 'b' referenced before assignment
10 Antworten
+ 5
You can also put global b in the first line of the function, that make b a global variable and now you can use it in that function, if want to use b again in another function you would need to write global b again. It looks like this:
b = [1,2,3]
def add(n):
global b
print(b)
b += [n]
add(4)
+ 3
Use b.append(n) instead of b+=[n] to avoid UnboundLocalError
+ 2
Using global is a very useful thing that i discovered learning extra stuff in internet
+ 1
Solomoni Railoa Thank you, but maybe you missed the point.
The print(b) inside add(n) has already output [1, 2, 3]
+ 1
Solomoni Railoa Thanks, that's it!
+ 1
Just make it global
+ 1
Just try to global the b varable, like:
a = [1, 2, 3]
a += [4]
print(a) # [1, 2, 3, 4]
b = [1, 2, 3]
def add(n):
global b
print(b) # [1, 2, 3]
b += [n]
add(4)