This question already has answers here:
UnboundLocalError trying to use a variable (supposed to be global) that is (re)assigned (even after first use)
(14 answers)
Closed 12 days ago.
Im playing around with functions and I never was able to understand why I couldn't change a variable. It always gives me an error.
Iv'e tried googling it but nothing really worked. Could someone help me out with this?
x = 1
def run():
print(x)
x += 1
run()
Since you are assigning to x, you need to declare it as global.
def run():
global x
print(x)
x += 1
Otherwise, the assignment makes it a local variable, one you try to print before assigning to it (and one that isn't initialized before you try to increment it).
Related
This question already has answers here:
UnboundLocalError trying to use a variable (supposed to be global) that is (re)assigned (even after first use)
(14 answers)
Closed 5 months ago.
If we run this code
a = 1
def foo():
b = a + 2
print(b)
foo()
it works.
But if we run this code
a = 1
def foo():
b = a + 2
print(b)
a = a + 4
print(a)
foo()
it doesn't work.
Question:
why in the first example b = a + 2 works without errors but in the second example the same line of code b = a + 2 is broken?
why if there is no reassignment of a we can get a from a global scope but if there is a reassignment we don't have an access to a even if new local a doesn't even exist yet (because the reassignment isn't finished).
Question: Why [...] the first example works without errors but in the second example the same line of code is broken?
Because in the first example, you're only reading from a global a, then writing to a local b.
In the second example, a is assumed to be a local too (since you're not declaring global a), and it has no value when you're trying to read it in the first line, hence an error.
This is similar to JavaScript's Temporal Dead Zone, if that's familiar.
As for the question in your title:
Why it's impossible to reassign global name within local scope (without global keyword) with using the global name's value in reassignment?
You're not reassigning
a global name at all in either of your examples, since indeed you're not using the global keyword. In Python, you can always read a global (or "ambient") name; otherwise it'd be a pain to e.g. use any builtin function (since they're not locals), and having a special exception for builtins would be, well, a special exception, and those aren't nice.
This question already has answers here:
UnboundLocalError trying to use a variable (supposed to be global) that is (re)assigned (even after first use)
(14 answers)
Closed 3 years ago.
I am relatively new to python and I can't understand why does this throws an error.
ar=''
def decToBin(no):
while(no>0):
ar=ar+str(no%2)
no=no//2
print(ar[::-1])
decToBin(4)
code that works
def decToBin(no):
ar=''
while(no>0):
ar=ar+str(no%2)
no=no//2
print(ar[::-1])
decToBin(4)
The scope of the "ar" variable is supposed to be global and should be accessible inside the function. Can anyone explain why the former isn't working?
The issue is this line:
ar=ar+str(no%2)
You are referencing it, before it has been assigned.
Try this instead:
ar = ''
def decToBin(no):
while(no>0):
#ar=ar+str(no%2)
no=no//2
print((ar+str(no%2))[::-1])
decToBin(4)
Changing decimal to binary is easy with numpy:
import numpy as np
np.binary_repr(4, width=None)
This question already has answers here:
UnboundLocalError trying to use a variable (supposed to be global) that is (re)assigned (even after first use)
(14 answers)
Closed 7 years ago.
I'm a bit confused as to how Python's variable scope system works. Say I have situation like this:
a = 10
def test():
print(a)
Then everything works just as I expect. Python first looks for a local variable a, fails to find it and then searches for a global variable.
However, in a situation like this:
a = 10
def test():
print(a)
a += 1
print(a)
Python throws an UnboundLocalError exception, apparently originating from line 3 (print(a)). To me it seems that at least to this line nothing has changed, and I don't understand why there is an exception anyway.
Since python does not have variable declarations, every variable assignment inside the scope of a function is considered local. So, you always have to specify that that variable is a global one:
a = 10
def test():
global a
print(a)
a += 1
print(a)
test()
This question already has answers here:
UnboundLocalError trying to use a variable (supposed to be global) that is (re)assigned (even after first use)
(14 answers)
Closed 8 years ago.
I have found a similar question Python variable scope error. It's related to immutable variable. But when I test mutable variable, I don't know how Python interpreter decides the scope of the variable.
Here's my sample code:
def test_immutable():
a = 1
b = 2
def _test():
print(a)
print(b)
a += 1
print(a)
_test()
def test_mutable():
_dict = {}
def _test():
print(_test.__dict__)
_dict['name'] = 'flyer'
print('in _test: {0}'.format(_dict['name']))
_test()
print(_dict['name'])
if __name__ == '__main__':
# test_immutable() # throw exception
test_mutable() # it's ok
Immutable vs mutable has nothing to do with variable scoping. Variables are just names, and always work the same way. Scoping is even decided at compile time, long before Python knows what you're going to assign to them.
The difference between your two functions is that the first one assigns directly to a with the += operator, which causes a to become a local. The second one assigns to a key inside _dict, which ultimately calls a method on the dict object, and doesn't affect the variable's scoping.
This question already has answers here:
Using global variables in a function
(25 answers)
Closed 8 years ago.
I've been having trouble with the "def" function. I know this question has already been asked, but the answer didn't satisfy me and I didn't see how to apply it to my code. I'm trying to make the the popular game 2048 in Python. Basically, when I define the function that makes the entire board move left, it bites me with the error: UnboundLocalError: local variable referenced before assignment. It seems that I have to define the variables "bone" and "btwo" in somewhere that isn't, like, global. But I am yet to figure out how to get that working. Setting parameters in my moveleft() function isn't working, e.g moveleft(bone,btwo). So I'm at my wit's end.
Now, I'll include the entire code, all commented up, but the part I think has the problem is where I define the function moveleft(). Also, if there are any outstanding stupid bits of code, please tell me. Also, try and keep it simple, I'm pretty rubbish with programming and its associated phrases and terms. This is only my 3rd attempt at a code.
I realise I'm asking a lot, but I would really, really, appreciate help with this.
Code:
http://pastebin.ca/2824228
Minimized version:
bone, btwo = 1, 2
def move_left():
if bone == 1: print("bone is 1")
if btwo == 2: print("btwo is 2")
btwo = 3
bone = 2
move_left()
If you are writing to a global variable inside a function, then you need to explicitly say that you are referring to a global variable. So put this as the first line in your function:
global bone, btwo, bthree, bfour, bfive, bsix, bseven, beight, bnine
And, why don't you use a list instead of defining 9 variables?