+ 1

Python Variable Scope ;UnboundLocalError;python global variable concept

list1 = [10, 20] def funSample(): print(list1) #list1 is global variable list1 = ['new value1', 'new value2'] print(list1) funSample() The above code caused error=> "UnboundLocalError: local variable 'list1' referenced before assignment" but iam trying to print list1 that is global variable then reassign new value what is the reason to cause this error? ------------------------- and i tried it again after removing the 1st print statement, error solved but my doubt what is the reason that error list1 = [10, 20] def funSample(): #print(list1) list1 = ['new value1', 'new value2'] print(list1) funSample() i'm new to python ,thanks in advance

30th Jan 2021, 6:33 PM
Akshay
Akshay - avatar
3 Antworten
+ 3
So python is weird or maybe not. The error is because you are assigning to the list1 with new values inside the function without declaring it global. So inorder to solve the problem you need to declare the variable list1 as global inside the function. Remember only to access a global variable inside a function there is no need to use global keyword. Akshay check out this code[updated] https://code.sololearn.com/ca6lNA0PNwjr/?ref=app
30th Jan 2021, 6:42 PM
minirkk
minirkk - avatar
+ 2
The second version of the function works because you define a local list1. In first version, python does not know what list1 is: it can't tell, that you mean the list1 outside the function. So before the first print() in this version, you need to tell python that you mean the global list1 (global list1)
30th Jan 2021, 6:49 PM
Lisa
Lisa - avatar
+ 1
RKK thanks for your reply I added global keyword and error resolved
30th Jan 2021, 6:50 PM
Akshay
Akshay - avatar