So I was having trouble understanding the basics of global variable as I am a beginner in python. I wanted to try to change a global variable but unfortunate it didn't work. Could any of you explain and help my fix my problem. Thanks!!
global x
x = 10
def NEWX():
print (x)
x = x + 5
print (x)
print (x)
NEWX()
print(x)
#this displays 10 10 15 10
Try this refactor:
x = 10
def new_x():
global x
print(x)
x = x + 5
print (x)
print(x)
new_x()
print(x)
# prints 10 10 15 15
I was unable to run your original code, it complained about x being undefined in the function. Within the scope of the function, x is unknown. It's known at the higher scope, but not in your function. That's why the global x statement needs to be in the function - to let python know to use the x from the outer scope.
x = 10
def NEWX():
global x
print (x)
x = x + 5
print (x)
print (x)
NEWX()
print(x)
Global variable rules:
global keyword outside a function has no effect
Variable outside a function is global by default
global keyword is needed to read and write global variable within a function
In your code, you are first printing the value of x. The function NEWX(): is then called which prints x, then adds 5 onto x and prints the new value. After the function is called, x is printed again.
To understand what is happening, check out this example that contains the fix:
x = 10
def NEWX():
print (x)
global x
x = x + 5
print (x)
print (x)
NEWX()
print(x)
Related
please check the code below.
x = 10
z = 30
def Rohan():
y = 15
x = 20
print(x,y,z)
global z
global x
z += 5
print (x,y,z)
Rohan()
While calling Rohan(), I am getting an error that reads "SyntaxError: name 'z' is used prior to global declaration
"
Please help me with the concepts of Global Variables and Local variables and what's causing the error.
I was trying to understand global and local variables in python and tried out the below-mentioned code but for some reason, the show() statement runs fine and I understand that but the print(x) statement below the show() prints 13 while I was expecting it to print 15
def show():
x=10
x+=5
print(x)
show()
print(x)
That print statement outside the function should not work at all. If you define a variable inside of a function you cant call it outside of it.
Also if your code looks like this:
x = 13
def show():
x = 10
x += 5
print(x)
show()
print(x)
the second print statement will still return 13, because by writing x = 10 you are creating a new variable named x inside the function, which will not be accessible outside this function.
x is probably defined before the function
try to not use the same variable name more than once
assuming x is not defined before this, this code should work
def show():
x = 10
x += 5
return x
show()
print(x)
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)
Using global variables in a function
(25 answers)
Closed 2 years ago.
My code
x = 10
def fun():
x = x + 2
print(x)
fun()
print(x)
And the output error
UnboundLocalError: local variable 'x' referenced before assignment
You have to pass global x in the def fun() as no variable named x is assigned in fun(). Here is the code:
x = 10
def fun():
global x
x = x + 2
print(x)
fun()
print(x)
Output
>>> 12
>>> 12
OR
You can also simply pass an argument, but this makes a difference in the values of x:
x = 10
def fun(x):
x = x + 2
print(x)
fun(x)
print(x)
Output
>>> 12
>>> 10
Your variable x, that you're trying modify in the function fun(), is of global scope. Hence, you can't access it inside the function like that. However, you can use:
x = 10
def fun():
global x
x = x + 2
print(x)
fun()
print(x)
Appending global x, will allow the function to modify the variable x which is in global scope.
You don't give x as the parameter to the function. That's why.
x = 10
def fun(x):
x = x + 2
print(x)
fun()
print(x)
I am really new to programming and Python, so please really forgive me for my ignorance.
I just learned that using global can make a variable inside function be a global one.
However, I discovered something not with my expectation:
I tried the following code in Python 3.8 (forgive me for my ignorance as I don't know what else information I should provide):
>>> x = 0
>>>
>>> def function():
... if False:
... global x
... x = 1
...
>>> function()
>>> print(x)
and the result is 1.
However, I expected the code to have the same effect as the following code:
>>> x = 0
>>>
>>> def function():
... x = 1
...
>>> function()
>>> print(x)
which the result should be 0.
In my mind, the statement inside if False should not be executed, so it sounds strange to me.
Also, personally, I think that in some situation I would expect the variable inside a function, whether local or global, to be dependent on other codes... what I mean is, I would like to change if False to something like if A == 'A', while (I hope) I can control whether the x is global/local according to my conditional statement.
I tried to change if to while, but it's the same... there isn't a infinite loop, but the code global x is still executed/compiled...
I admit that it may sounds naive, and perhaps it just won't work in Python, but I really wonder why... It seems that the code global x is unreachable, but how come it is not ignored?
Can anyone please tell me about the reason? I would like to know more about the mechanism behind compilation(?)
Any help would be appreciated, thank you!
In python the global statement (and the nonlocal statement) are very different from the normal python code. Essentially no matter where a global statement in a function is, it influences always the current codeblock, and is never "executed". You should think more of it as a compiler directive instead of a command.
Note that the statement itself must come before any usage of the variable it modifies, i.e.
print(x)
global x
is a syntax error. The global statement can only modify variable behavior in the whole codeblock, you can't first have a non-global variable that later gets global and you can also not have conditional global variable
(I couldn't really find good documentation for this behavior, here it says "The global statement is a declaration which holds for the entire current code block." and "global is a directive to the parser. It applies only to code parsed at the same time as the global statement." but that doesn't seem super clear to me.)
There are more compiler directives in python, although they don't always look like one. One is the from __future__ import statements which look like module imports but change python behavior.
Global is not in execution path but in a scope. The scope is whole function. Statements like if for don't make scopes. If you use any assignment you create local variable. The same with global or nonlocal you bind symbol to variable from outside.
As Stanislas Morbieu typed, see doc.
Programmer’s note: global is a directive to the parser. It applies only to code parsed at the same time as the global statement.
Not at execution time.
x = 1
def fun():
y = x + 1
print(f'local x = {x}, y = {y}')
fun()
print(f'global x = {x}')
# Output:
# local x = 1, y = 2
# global x = 1
In example above, y uses global x (and adds 1).
x = 1
def fun():
y = x
x = y + 1
print(f'local x = {x}')
fun()
print(f'global x = {x}')
# Output:
# UnboundLocalError: local variable 'x' referenced before assignment
Look at last example. It doesn't assign y from global x because assignment in second line creates local x and y can not read local x before x assignment. The same with:
x = 1
def fun():
if False:
x += 1
fun()
# Output
# UnboundLocalError: local variable 'x' referenced before assignment
x assignment creates local variable.
If you want to change global variable under condition you can use globals().
x = 1
def set_x(do_set, value):
if do_set:
globals()['x'] = value
print(f'global x = {x} (init)')
set_x(False, 2)
print(f'global x = {x} (false)')
set_x(True, 3)
print(f'global x = {x} (true)')
# Output
# global x = 1 (init)
# global x = 1 (false)
# global x = 3 (true)
Proxy
I you want to decide with variable you want to use later (in the same scope) you need some kind of proxy IMO.
x = 1
def fun(use_global):
x = 2 # local
scope = globals() if use_global else locals()
scope['x'] += 1
print(f'local ({use_global}): x = {scope["x"]}')
print(f'global: x = {x} (init)')
fun(False)
print(f'global: x = {x} (false)')
fun(True)
print(f'global: x = {x} (true)')
# Output:
# global: x = 1 (init)
# local (False): x = 3
# global: x = 1 (false)
# local (True): x = 2
# global: x = 2 (true)
Maybe you can think about refactoring of your code if you need it.
If you can change local variable name (if not use globals() as above), you can proxy:
use dict (like in example above)
use list (x=[1]) and usage x[0]
use object (with builtin dict), example:
class X:
def __init__(self, x):
self.x = x
x = X(1)
def fun(use_global):
global x
my_x = x if use_global else X(2)
my_x.x += 1
print(f'local ({use_global}): x = {my_x.x}')
print(f'global: x = {x.x} (init)')
fun(False)
print(f'global: x = {x.x} (false)')
fun(True)
print(f'global: x = {x.x} (true)')
# Output:
# global: x = 1 (init)
# local (False): x = 3
# global: x = 1 (false)
# local (True): x = 2
# global: x = 2 (true)
Note. Variables in Python are only references. It is way you can not change x = 1 without global (or globals()). You change reference to local value 1.
But you can change z[0] or z['x'] or z.x. Because z referents to list or dict or object and you modify it content.
See: https://realpython.com/python-variables/#object-references
You can check real object by id() function, ex. print(id(x), id(my_x)).
As per the Python documentation, global is a directive to the parser so it is taken into account before the execution, therefore it does not matter if the code is reachable or not. The variable is global for the entire scope, which is the function in your case.
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 years ago.
x=100
def fun2():
print x
x=10000
print x
fun2()
The above program showing local variable x reference before assignment. Why it is not printing
100
10000
x in the function is a local variable and can't access the other local variable you define first because they are in different scope.
Add global x to the start of your function or define x inside the function.
You appear to not know about variable scoping.
The variable x does not exist in the function scope.
You have to place global x before your print statement in order to access the global variable x.
x = 1 # Global x
def f():
x = 2 # function-local x
print(x) # prints 2
f()
print(x) # prints 1 because it uses the global x which remains unchanged
If you want that to work you need to specify inside the function that the x variable you are using is the one in the global scope by using the global keyword.
x=100
def fun2():
# Add this line
global x
print x
x=10000
print x
fun2()
Below code will print the value of x -> 100, as it is there in main scope #samba, but when you change the value of it doesn't work that way as it is not defined in the function.
x = 100
def fun2():
print(x)
fun2()
This doesn't work as the same way:
x = 100
def fun2():
print(x)
x = 1000
print(x)
fun2()
and through error:
UnboundLocalError: local variable 'x' referenced before assignment
x is a local variable and not initialised in function fun2().
You need to understand variable scoping here, Please check Global and Local variable scope
If you want to use it globally use global keyword in your function.
Because u assigned variable before function.
Just try this
def fun2():
x=100
print x
x=10000
print x
fun2()
It will output 100 and 1000