0

Global and local variables

Can anyone please explain why below gives the error “ local variable ‘a’ referenced before assignment” ? a=[1,2,3] def add(n): a+=[n] add(4)

2nd Jun 2019, 4:51 PM
Sahil Rana
Sahil Rana - avatar
3 ответов
+ 3
a=[1,2,3] def add(n): global a a+=[n] print(a) add(4) you have to use global keyword if you have to code like you asked in question or you have to code like choe said
2nd Jun 2019, 5:30 PM
Geek
Geek - avatar
+ 2
better to do this a = [1,2,3] def add(n): a.append(n) print(a) add(4)
2nd Jun 2019, 5:02 PM
Choe
Choe - avatar