+ 4

it shows [UnboundLocalError ] , i cant understand why??

x = 300 def myfunc(): print(x) x=500 myfunc() print(x) please run above code... it says error and i dont know why?☹️☹️ if x=500 is removed then it works well 😕 or write x=500 before print(x) then it also works well😒😒

24th Feb 2020, 5:30 PM
BlackShadow334
BlackShadow334 - avatar
5 odpowiedzi
+ 5
yes because it tried to modify a value outside its own scope. as long as the outside variable doesnt change in any way from inside a function, it'll be fine you dont need to define global. but changing a value outside its own function is no go. unless you define global in the function as i shown before.
24th Feb 2020, 5:51 PM
Taste
Taste - avatar
+ 5
theres a rule about functional programming where function should not have a side effect. and modifying global variable also count as a side effect. to solve this you can either obey. def myfunc(x): print(x) x=500 return x x = myfunc(x) print(x) or simply tell python that you're fine with it by bind the global variable to local scope def myfunc(x): global x print(x) x=500
24th Feb 2020, 5:39 PM
Taste
Taste - avatar
+ 5
Yep, print(x) just outputs the value of the global variable 'x' in that case.
24th Feb 2020, 5:51 PM
Russ
Russ - avatar
+ 4
This is my understanding. Because you have created the (local) variable 'x' within the function, the function doesn't recognise the global variable 'x'. Because print(x) was called before the creation of the local variable 'x', the error is triggered (variable referenced before assignment).
24th Feb 2020, 5:36 PM
Russ
Russ - avatar
+ 3
Russ Taste when x=500 is removed then it shows no error ie. if we remove x=500 then, it doesnt need to define x as global. 😛
24th Feb 2020, 5:45 PM
BlackShadow334
BlackShadow334 - avatar