UnboundLocalError: local variable 'r' referenced before assignment [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)
Closed 9 years ago.
I'm having an issue with variable and function. Here is a simple code:
r = 0
list = ['apple','lime','orange']
def list_list(x):
for i in x:
r +=1
print r
list_list(list)
Error:
UnboundLocalError: local variable 'r' referenced before assignment
I know it must be something simple. I started to do my script using functions instead straight code.

You should rewrite your function to take r as an argument if you want to define it outside of your function:
def my_func(some_list, r=0):
# do some stuff
Basically, you have a problem with scope. If you need r outside of the function, just return it's value in a tuple:
def my_func(some_list, r=0):
# do some stuff
return new_list, r
my_list = [1,2,3,4,5]
different_list, my_outside_r = my_func(some_list, 0)

The r within the function isn't the same as the one outside the function, so it hasn't been set yet.

You shoudld put r = 0 inside the function. But if you want the length of the list just use len(list)
Also try to avoid naming variables same as builtin names like list.

Related

How to understand global and local scopes 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)
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.

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.

How do I assign a global variable to a function's return? [duplicate]

This question already has answers here:
How do I pass a variable by reference?
(39 answers)
How to get/set local variables of a function (from outside) in Python? [duplicate]
(5 answers)
Closed 3 years ago.
How do I assign a global variable to a function's return? The only way I seem to be able to get it to work properly is to assign the variable to the function itself. When I run the code, the variable assignment performs the function on that line, which is not what I want. I only want an assignment so I can use the variable later.
def random_function():
x = 3.14
return x
This is what I'd like to happen but does not work:
pi = x
This works but runs the function in the console on that line which is not something I want:
pi = random_function()
print(pi)
If you're inside a function but want to assign a new value to a global, you have to declare the global first. Otherwise the identifier will be assumed to be a local variable. What I mean is this:
pi = -1 # declare your global
def random_function():
global pi
x = 3.14
pi = x # now works, after the `global` line above
return x
If I understand it right, you want to assign the return value of your function to a variable?
x = random_function()
I think that's how you can write it. You can use whatever variable you want.
You've answered your question already. To assign a global variable to a function's return value, simply assign the variable to the function's call;
def random_function():
x = 3.14
return x
pi = random_function()
You can print pi in the console if you want to see it's value. Not required.

Python Nested Function Variable 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 9 years ago.
I'm trying to do something along the following lines in python3:
i = 1337
def g():
print(i)
i = 42
g()
but get the following error
UnboundLocalError: local variable 'i' referenced before assignment
I think I understand what the error message means, but why is it the case? Is there any way to circumvent this?
In two words - when a given variable name is not assigned a value within a function then references to the variable will be looked up. Use global - and in such a case python will look for i in global scope:
i = 1337
def g():
global i
print i
i = 42
g()
You can read more on variable scopes in PEP-0227
If you really really want to do it that way, you'll need to get i from the global scope.
def g():
global i
print i
i = 42
However, generally you would be much better off changing how your code works to not require globals. Depending on how you are using it, that could be as simple as passing in i as a parameter and returning the changed value.
An example of Keeyai's suggestion of passing in i as a parameter:
i = 1337
def g(i):
print(i)
i = 42
g(i)
However, you never use the new value of i, so perhaps something like this makes more sense:
def g (i):
i = 42
return i
i = 1337
print g(i)

Categories