How to understand global and local scopes in Python? [duplicate] - python

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 5 months ago.
I am a novice in Python and wondering the situation below.
x = 1
def func():
print(x)
x = 2
return x
So I got the UnboundLocalError: local variable 'x' referenced before assignment.
But if I right understand - Python read and execute code row by row.
So in first statement inside function "print(x)" it must just relay global variable x which eq. 1, but instead I got the error.
Please explain, I think it simple.

I think your problem was explained as well in the FAQ of python docs
This is because when you make an assignment to a variable in a scope,
that variable becomes local to that scope and shadows any similarly
named variable in the outer scope. Since the last statement in foo
assigns a new value to x, the compiler recognizes it as a local
variable. Consequently when the earlier print(x) attempts to print the
uninitialized local variable and an error results.

Related

Why this statement produce a print error? [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)
Local variable referenced before assignment? [duplicate]
(5 answers)
Closed 11 months ago.
def f():
print(x)
def g():
print(x)
x = 1
x = 3
f()
x = 3
g()
It prints 3 when f is invoked, but the error message
UnboundLocalError: local variable 'x' referenced before assignment
is printed when the print statement in g is encountered. This happens because
the assignment statement following the print statement causes x to be local to g.
And because x is local to g, it has no value when the print statement is executed.
The above quote and code are from 《Introduction to Computation and Programming Using Python》
And here is my understanding through this explanation. Just wondering if this is valid:
The print statement in function f does not produce an error because it does not contain the name of x as a local variable, forcing the interpreter to search the stack frame with scope outside the definition of x and finding out that x binds to 3. Then use the value. While, in function g, there exists a local variable binds to number 1 after the print statement, the function already takes x as a local variable as x binds to some values in the function body. The interpreter does not search back to other stack frames with scope, hence the outer x bound will not be searched and used. Based on this, it has no value in x yet when the print statement is executed.

Python list += unexpected behavior in inner function [duplicate]

This question already has answers here:
Is it possible to modify a variable in python that is in an outer (enclosing), but not global, scope?
(9 answers)
UnboundLocalError trying to use a variable (supposed to be global) that is (re)assigned (even after first use)
(14 answers)
Closed 2 years ago.
I read in many places that += is an in-place operation, which does not create a new list. Given this, I would expect the inner function to be able to see and mutate the lst defined in outer(). Could someone explain what is going on here? I understand there are alternative ways to make it work as expected like lst.append(2). I am just trying to understand why it does NOT work.
There is a similar question regarding += on integers UnboundLocalError with nested function scopes
That question is easy to answer as integers are immutable so ctr += 1 actually declares a new name in the inner function, and that new name is referenced before a value is assigned. This argument does not apply to the case here since += on a list does not create new bindings.
def outer():
lst = [0]
def inner():
lst += [2]
inner()
outer()
UnboundLocalError: local variable 'lst' referenced before assignment

How to set variable within function def in python? [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)
UnboundLocalError: local variable … referenced before assignment [duplicate]
(2 answers)
Closed 2 years ago.
I have a simple code like this:
temp = 100
def my_fun():
temp += 10
return temp
After I call this function my_fun() I get an error
local variable 'temp' referenced before assignment
What's wrong with my code? I set temp before I call it. But still an error.
Thanks to all.
Best would be to pass it in:
def my_fun(temp):
temp += 10
return temp
temp = 100
temp = my_fun(temp)
But if you really want to access it from the outer scope, then use:
global temp
Edit: I see you amended your question - the reason for the error is the scope of the var. Within the function that variable only exists at the function level, and since you've not actually assigned it or passed it in, it doesn't exist when you try and increment it.

python scoping and run order in building namespace [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 6 years ago.
Why does this not work in python?, where I can access the enclosing scope (here global scope) when there are no other references to the same variable but can't when there are.
Does the interpreter look further down the function first before for the variable definition, finds it so assumes it is only a local variable which hasn't yet been assigned a value? What's the run order of the interpreter here?
> a = 5
> a
Out[3]:
5
> def closure():
print(a)
> closure()
5
> def closure():
print(a)
a = "another"
return a
> closure()
UnboundLocalError: local variable 'a' referenced before assignment
Add global a to the first line of the function.

When does my function will go to previous scopes to look for a variable? [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)
Is it possible to modify a variable in python that is in an outer (enclosing), but not global, scope?
(9 answers)
Closed 6 months ago.
in python 3.0 from what i know when i'm using variables that aren't found in the local scope it will go all the way back until it reaches the global scope to look for that variable.
I have this function:
def make_withdraw(balance):
def withdraw(amount):
if amount>balance:
return 'insuffiscient funds'
balance=balance-amount
return balance
return withdraw
p=make_withdraw(100)
print(p(30))
When i insert a line:
nonlocal balance
under the withdraw function definition it works well,
but when i don't it will give me an error that i reference local variable 'balance' before assignment, even if i have it in the make_withdraw function scope or in the global scope.
Why in other cases it will find a variable in previous scopes and in this one it won't?
Thanks!
There are too many questions on this topic. You should search before you ask.
Basically, since you have balance=balance-amount in function withdraw, Python thinks balance is defined inside this function, but when code runs to if amount>balance: line, it haven't seen balance's definition/assignment, so it complains local variable 'balance' before assignment.
nonlocal lets you assign values to a variable in an outer (but non-global) scope, it tells python balance is not defined in function withdraw but outside it.

Categories