+ 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😒😒
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.
+ 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
+ 5
Yep, print(x) just outputs the value of the global variable 'x' in that case.
+ 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).