+ 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

7th Jan 2022, 2:42 AM
FanYu
FanYu - avatar
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)
7th Jan 2022, 10:01 PM
Marcos Ezequiel Hernández Damaglia
Marcos Ezequiel Hernández Damaglia - avatar
+ 3
Use b.append(n) instead of b+=[n] to avoid UnboundLocalError
7th Jan 2022, 11:51 AM
Vitaly Sokol
Vitaly Sokol - avatar
+ 2
Using global is a very useful thing that i discovered learning extra stuff in internet
7th Jan 2022, 10:01 PM
Marcos Ezequiel Hernández Damaglia
Marcos Ezequiel Hernández Damaglia - avatar
+ 1
Solomoni Railoa Thank you, but maybe you missed the point. The print(b) inside add(n) has already output [1, 2, 3]
7th Jan 2022, 3:30 AM
FanYu
FanYu - avatar
+ 1
Solomoni Railoa Thanks, that's it!
7th Jan 2022, 4:08 AM
FanYu
FanYu - avatar
+ 1
Just make it global
8th Jan 2022, 9:59 AM
Yakesh Balaji Raja.P.
Yakesh Balaji Raja.P. - avatar
+ 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)
8th Jan 2022, 3:47 PM
FᄂӨЯΣПᄃ BΛЯDΉI
FᄂӨЯΣПᄃ BΛЯDΉI - avatar