How can I manage the scope problem in Python [duplicate] - python

This question already has answers here:
Python function global variables? [duplicate]
(6 answers)
Closed last year.
I have the following code:
x = 1
def increaseX(number):
x += number
increaseX(2)
print(x)
I want to increase a glob variable via the function increaseX, what is the best way to do this?

global keyword is what you need:
x = 1
def increaseX(number):
global x
x += number
increaseX(2)
print(x)
Otherwise, Python tries to find x in local namespace because of += (something like x = x + number) and because in the right hand side of the assignment there is no x defined, you will get :
UnboundLocalError: local variable 'x' referenced before assignment

I tried this and it works, but I don't feel this is the best way
x = 1
def increaseX(number):
global x
x += number
increaseX(2)
print(x)

Related

My variables updated in a function don't work outside the function [duplicate]

This question already has answers here:
Python function global variables? [duplicate]
(6 answers)
Function not changing global variable
(4 answers)
Closed 1 year ago.
hi = 1
result = 0
def hello(x):
x = x + 10
result = x
helli(hi)
print(result)
Why does my code Output "0" and not 11?
You need to use the keyword global for that. Then edited values inside the function actually impact the variable from outside the function. This is not the recommended approach.
hi = 1
result = 0
def hello(x):
global result
x = x + 10
result = x
hello(hi)
print(result)
The recommended approach is, however, to return such value:
def hello(x):
return x + 10
hi = 1
result = 0
result = hello(hi)
print(result)

Could some explain the following behavior of global variable in python? [duplicate]

This question already has answers here:
In Python what is a global statement?
(5 answers)
Closed 4 years ago.
test.py
x = 10; # global variable
def func1():
print(x); # prints 10
def func2()
x = x + 1; # IDE shows error: "Unresolved reference of x(RHS of expression)
def func3()
global x;
x = x + 1; # This works
When x has a global scope, why doesn't func2() allow me to modify its value though it is accessible as seen in func1(). And why does it require explicit mention of "global" keyword as in case of func3() ?
You can access global variables but for modifying them it should be explicitly declared that variable is a global variable.
I think this link would be useful.
The reason behind it is that when you say x = x + 1, python thinks that you want a local variable x and then when reaches the x + 1 expression python finds out that the local variable x was mentioned but not assigned any value so it gets confused.

Python variables outside function [duplicate]

This question already has answers here:
Using global variables in a function
(25 answers)
Closed 7 years ago.
I'm trying to access the counter variable in my function, why doesn't it work and how do I resolve it?
Relevant code:
sum = 0
counter = 0
def newFibo(a, b) :
if(counter > 4000000) :
return
c = a + b
sum += c
counter +=1
newFibo(b,c)
newFibo(1,2)
print(sum)
error: "local variable 'counter' referenced before assignment"
In Python, if you want to modify a global variable inside a function, you have to declare it as global inside the function:
def newFibo(a, b) :
global counter, sum
..............
Note that you don't need it if the variable is only read inside the function but not modified.
You need to use the keyword global to tell python that a variable is outside the current function.
So, basically, add global sum, counter right after def newFibo(a, b):.

Python global variable/scope confusion [duplicate]

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 7 years ago.
I've started teaching myself python, and have noticed something strange to do with global variables and scope.
When I run this:
x = 2
y = 3
z=17
def add_nums():
y = 6
return z+y
The result of 23 is printed...
However, when I expand the return to be:
x = 2
y = 3
z=17
def add_nums():
y = 6
z = z + y
return z
I get the following error on line 6:
Local name referenced but not bound to a value.
A local name was used before it was created. You need to define the
method or variable before you try to use it.
I'm confused as why I am getting an error here, as z is global an accessible.
When a variable is on the left side of an equal sign python will create a local variable. When the variable is on the right side of the equal sign python will try to look for a local variable and if he can't find one then it will use a global variable. In your example, z is on the right and left side of the equal sign, to avoid ambiguities python raises an error. You need to use the global syntax to avoid this:
x = 2
y = 3
z = 17
def add_nums():
global z
y = 6
z = z + y
return z
Python determines scope by binding operations. Assignment is a binding operation, as is importing, using a name as a target in except .. as, with .. as or a for loop, or by creating a function or a class.
When a name is bound in a scope, it is local to that scope. If a name is used but not bound, it is non-local; the compiler will determine at compile time what the scope should be then. In your case there is no parent scope other than the global scope, so any name not bound to is considered a global.
Since your second example binds to z (you used z =, an assignment), the name is local to the function.
If a name is bound to in a scope but you want to tell Python that it should be global anyway, you need to do so explicitly:
x = 2
y = 3
z=17
def add_nums():
global z
y = 6
z = z + y
return z
The global z line tells the compiler that z should be a global, even though you bind to it.
Let's analyse the marked line.
x = 2
y = 3
z = 17
def add_nums():
y = 6
z = z + y <--- THIS LINE
return z
z ... a new local variable is created
= ... we are going to assign a value to it
z ... this variable exists (the new local one) but it has no value yet.
+ y ... this part is not reached.
The result is an error message "UnboundLocalError: local variable 'z' referenced before assignment".
If you want the names y and z inside the function body to reference your global variables when you assign something to them, you must declare them like this:
x = 2
y = 3
z=17
def add_nums():
global y
global z
y = 6
z = z + y
return z
Otherwise, when you perform an assignment to the variables y and z inside the function, you create different names that exist only in the local scope of the function.
As pointed out in the comments, you can reference a global variable and even modify it if it is mutable (i.e. append something to a list) without explicitly declaring it global as long as you don't try to assign to it.

python : local variable is referenced before assignment [duplicate]

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.
Here is my code :
x = 1
def poi(y):
# insert line here
def main():
print poi(1)
if __name__ == "__main__":
main()
If following 4 lines are placed, one at a time, in place of # insert line here
Lines | Output
---------------+--------------
1. return x | 1
2. x = 99 |
return x | 99
3. return x+y | 2
4. x = 99 | 99
In above lines it seems that global x declared above function is being used in case 1 and 3
But ,
x = x*y
return x
This gives
error : local variable 'x' is reference before assignment
What is wrong in here ?
When Python sees that you are assigning to x it forces it to be a local variable name. Now it becomes impossible to see the global x in that function (unless you use the global keyword)
So
Case 1) Since there is no local x, you get the global
Case 2) You are assigning to a local x so all references to x in the function will be the local one
Case 3) No problem, it's using the global x again
Case 4) Same as case 2
When you want to access a global variable, you can just access it by its name. But if you want to change its value, you need to use the keyword global.
try :
global x
x = x * y
return x
In case 2, x is created as a local variable, the global x is never used.
>>> x = 12
>>> def poi():
... x = 99
... return x
...
>>> poi()
99
>>> x
12

Categories

Resources