Been looking around and can't find an answer.
So I call either raw_input() or input() to fill out a simple variable. But instead of running the function, I get
UnboundLocalError: local variable 'input' referenced before assignment
My code doesn't have 'input()' anywhere before that first call, and never makes a variable sharing the name. Same happens for 'raw_input()'. I'm confused here, as calls to the functions work fine in other code, and also on the console, but for some reason throw errors on this. No previous calls. Funny enough, it worked on my first run of the code, but now doesn't. What am I looking for?
Edit: Someone asked for the code. Not much to show.
end = False
lightsoff = []
lightson = []
bias = []
i = 0
while not end:
print "Set #" + str(i + 1) +", LED off: ",
offFile = input()
EDIT: To correct here, a variable named 'input' is referred to much later in the code (it's long). I wrote a couple of references backwards. I didn't know Python made a list (or something) of what's going to be a local variable before running, thus throwing up problems like this.
I suspect your code looks a bit like:
>>> def x():
... input = input()
... print(input)
...
>>> x()
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "<stdin>", line 2, in x
UnboundLocalError: local variable 'input' referenced before assignment
>>>
The problem is that you've created a variable called 'input', and then trying to get something from it before it exists.
>>> def y():
... val = input()
... print(val)
...
>>> y()
Would work a bit better. In python (and most dynamic languages) functions are kind of values too - so you can use the name of a function just like you would any other variable.
So a good idea is to not name a variable the same as a function.
Does that help?
Related
I got NameError for calling test_gobject, but the funny thing is I never called this function name. I called test_gobjectpy()
Can you explain it to me why Python decide to call the wrong function name (see error output)
Maybe it has some problems because I have a string with the same name as function?!
file name test_dyn_fun.py
second_path = ['test_gobject.py', 'st1.py', 'test_show_desktop.py', 'download_img.py', 'test_dump.py']
print("second_path", second_path)
print()
for i in second_path:
#func = create_dyn_func(i)
tmp = i.replace(".", "") #rm dot for function name
print("tmp =", tmp)
exec(f"def {tmp}(): print({i})")
print()
print(dir(test_gobjectpy))
print()
print(locals())
test_gobjectpy()
Error output:
Traceback (most recent call last):
File "/home/manta/Coding/test_dyn_fun.py", line 13, in <module>
test_gobjectpy()
File "<string>", line 1, in test_gobjectpy
NameError: name 'test_gobject' is not defined
In your loop you create functions, the first one created is effectively created like this:
i = 'test_gobject.py'
tmp = 'test_gobjectpy'
exec(f"def {tmp}(): print({i})")
So, it's as if you ran:
exec("def test_gobjectpy(): print(test_gobject.py)")
For Python to print test_gobject.py, it tries to access an object called test_gobject and its attribute .py.
That's what is causing the error. The fact that test_gobject.py looks like a filename to you doesn't matter, it's just names of variables to Python, the way you wrote it.
What would you expect to happen if you called this function?
def test_gobjectpy():
print(test_gobject.py)
More in general, as a beginning programmer, it's generally best to stay away from stuff like exec() and eval(). It's very common for new Python programmers to think they need this, or that it somehow solves a problem they have, but it's generally the worst solution to the problem and rarely actually a good solution at all. (not never, just rarely)
So I have a string which is a function like
code = """def somefn(x):
return x + x
y = somefn(z)"""
and I am trying to run this in another function like
def otherfn(codestr):
z = 2
exec(codestr)
return y
otherfn(code)
but it gives me the error:
Traceback (most recent call last):
File "C:/Users/Admin/Desktop/heh.py", line 11, in
otherfn(code)
File "C:/Users/Admin/Desktop/heh.py", line 9, in otherfn
return y
NameError: name 'y' is not defined
it works fine outside the function like
z=2
exec(codestr)
print(y)
it finds y just fine but not sure why it is bugging out when it is in the function.
How can I fix this? Is it something to do with globals() and locals()? Using Python 3.6 btw.
There are several problems with your code. First of all, you have an indentation problem - the y gets 'defined' inside the somefn() function, after the return so it never actually gets the chance to get onto the stack. You need to redefine your code to :
code = """def somefn(x):
return x + x
y = somefn(z)"""
But that's just the tip of the iceberg. The greater issue is that exec() cannot modify the local scope of a function. This is due the fact that Python doesn't use a dict for lookup of variables in the local scope so all changes from the exec() do not get reflected back to the stack to enable lookup. This causes a weird issue where exec() seemingly changes the locals() dictionary, but Python still throws a NameError:
def otherfn(codestr):
z = 2
exec(codestr)
print(locals()["y"]) # prints 4
return y # NameError
otherfn(code)
This is an intended behavior, as explained in the issue4831, and further pontificated in the official docs:
Note: The default locals act as described for function locals() below: modifications to the default locals dictionary should not be attempted. Pass an explicit locals dictionary if you need to see effects of the code on locals after function exec() returns.
But if you have to reflect the changes you can just do a post-exec local scope update:
def otherfn(codestr):
z = 2
locals_ = locals()
exec(codestr, globals(), locals_)
y = locals_["y"]
return y
otherfn(code)
This question already has answers here:
Using global variables in a function
(25 answers)
UnboundLocalError trying to use a variable (supposed to be global) that is (re)assigned (even after first use)
(14 answers)
Closed 7 months ago.
I'm trying to add or subtract from a defined variable, but how can I overwrite the old value with the new one?
a = 15
def test():
a = a + 10
print(a)
test()
Error message:
Traceback (most recent call last):
File "test.py", line 7, in <module>
test()
File "test.py", line 4, in test
a = a +10
UnboundLocalError: local variable 'a' referenced before assignment
The error that you get when you try to run your code is:
UnboundLocalError: local variable 'a' referenced before assignment
… which, on the face of it, seems strange: after all, the first statement in the code above (a = 15) is an assignment. So, what's going on?
Actually, there are two distinct things happening, and neither of them are obvious unless you already know about them.
First of all, you actually have two different variables:
The a in your first line is a global variable (so called because it exists in the global scope, outside of any function definitions).
The a in the other lines is a local variable, meaning that it only exists inside your test() function.
These two variables are completely unrelated to each other, even though they have the same name.
A variable is local to a function if there's a statement assigning to it inside that function - for instance, your a = a +10 line.
Even so, the error still looks strange - after all, the very first thing you do inside test() is assign to a, so how can it be referenced beforehand?
The answer is that, in an assignment statement, Python evaluates everything on the right hand side of the = sign before assigning it to the name on the left hand side – so even though the assignment is written first in your code, a gets referenced first in that right hand side: a +10.
There are two ways you can get around this. The first is to tell Python that you really want the a inside test() to be the same a in the global scope:
def test():
global a
a = a + 10
print(a)
This will work, but it's a pretty bad way to write programs. Altering global variables inside functions gets hard to manage really quickly, because you usually have lots of functions, and none of them can ever be sure that another one isn't messing with the global variable in some way they aren't expecting.
A better way is to pass variables as arguments to functions, like this:
a = 15
def test(x):
x = x + 10
print(x)
test(a)
Notice that the name doesn't have to be the same - your new definition of test() just says that it accepts a value, and then does something with it. You can pass in anything you like – it could be a, or the number 7, or something else. In fact, your code will always be easier to understand if you try to avoid having variables with the same name in different scopes.
If you play with the code above, you'll notice something interesting:
>>> a = 15
>>> test(a)
25
>>> a
15
… a didn't change! That's because although you passed it into test() and it got assigned to x, it was then x that got changed, leaving the original a alone.
If you want to actually change a, you need to return your modified x from the function, and then reassign it back to a on the outside:
>>> a = 15
>>>
>>> def test(x):
... x = x + 10
... print(x)
... return x
...
>>> a = test(a)
25
>>> a
25
You're modifying a variable a created in the scope of the function test(). If you want the outer a to be modified, you could do:
a = 15
def test():
global a
a = a + 1
print(a)
test()
I would do it this way:
def test(a):
a = a +10
return a
print(test(15))
Note that in the version hereby proposed there are some things differing from yours.
First, what I wrote down would create a function that has, as an input, the value a (in this case set to 15 when we call the function -already defined in the last line-), then assigns to the object a the value a (which was 15) plus 10, then returns a (which has been modified and now is 25) and, finally, prints a out thanks to the last line of code:
print(test(15))
Note that what you did wasn't actually a pure function, so to speak. Usually we want functions to get an input value (or several) and return an input value (or several). In your case you had an input value that was actually empty and no output value (as you didn't use return). Besides, you tried to write this input a outside the function (which, when you called it by saying test(a) the value a was not loaded an gave you the error -i.e. in the eyes of the computer it was "empty").
Furthermore, I would encourage you to get used to writing return within the function and then using a print when you call it (just like I wrote in the last coding line: print(test(15))) instead of using it inside the function. It is better to use print only when you call the function and want to see what the function is actually doing.
At least, this is the way they showed me in basic programming lessons. This can be justified as follows: if you are using the return within the function, the function will give you a value that can be later used in other functions (i.e. the function returns something you can work with). Otherwise, you would only get a number displayed on screen with a print, but the computer could not further work with it.
P.S. You could do the same doing this:
def test(a):
a +=10
return a
print(test(15))
a = 15
def test():
global a
a = a + 10
print(a)
test()
If you want to change the values of local variables inside a function you need to use the global keyword.
The scope of the variable is local to the block unless defined explicitly using keyword global. There is another way to access the global variable local to a function using the globals function:
a = 15
def test():
a = globals()['a']
a += 10
print(a)
test()
The above example will print 25 while keeping the global value intact, i.e., 15.
The issue here is scope.
The error basically means you're using the variable a, but it doesn't exist yet. Why? The variable a has not been declared in the test() function. You need to "invite" global variables before using them.
There are several ways to include a variable in the scope of a function. One way is to use it as a parameter like this:
def test(number):
number = number + 10
print(number)
Then implement it as:
test(a)
Alternatively, you could also use the global keyword to show the function that a is a global variable. How? Like this:
def test():
global a
a = a + 10
print(a)
Using the global keyword just tells the test where to look for a.
With the first method, you can't modify the global variable a, because you made a copy of it and you're using the copy. In the second method, though, any changes you make in the function test() to a, will affect the global variable a.
# All the mumbo jumbo aside, here is an experiment
# to illustrate why this is something useful
# in the language of Python:
a = 15 # This could be read-only, should check docs
def test_1():
b = a + 10 # It is perfectly ok to use 'a'
print(b)
def test_2():
a = a + 10 # Refrain from attempting to change 'a'
print(a)
test_1() # No error
test_2() # UnboundLocalError: ...
Your error has nothing to do with it being already defined…
A variable is only valid inside its so-called scope: If you create a variable in a function it is only defined in this function.
def test():
x = 17
print(x) # Returns 17
test()
print(x) # Results in an error.
I'm currently taking a Python course, and got to the chapter in our book that talks about functions. (Please note, this is my first time learning any programming.)
One of the exercises I'm working on at the moment asks for me to turn a bunch of conditional statements into a function (i.e. generalization).
To make this brief, my problem is this:
After I define a function, let's say like so...
def count_letter(letter,string):
count = 0
for letter in string:
count += 1
print(count)
(That is the work, as far as I can recall, for what I typed up for the problem.)
I run the program, then call the function in the shell as usual...
(Example directly below)
>>> count_letter(a,bananana)
And I get the following output...
Traceback (most recent call last):
File "<pyshell#3>", line 1, in <module>
count_letter(a,bananana)
NameError: name 'a' is not defined
My teacher and everyone in our class can't figure out why we're getting such an error. We would understand if it was some other type of an error, but having the shell tell us an argument is 'undefined' (i.e. a variable, as we understand the error) is something we haven't been able to figure out.
We've been staring at the code for a week and still can't figure it out.
Any help would be very appreciated.
Afterthought: I'm trying to count the number of "a"s within "bananana" in the example. Thought I should clear the ambiguity there.
As written, a and bananana are the names of variables which should be defined in a similar way you defined the variable count. For example:
>>> character_to_search = 'l'
>>> text = 'Hello World'
>>> count_letter(character_to_search, text)
would be a correct syntax, because both character_to_search and text are undefined.
Another possibility is that instead of using actual variables, your intention was to pass strings directly to the function. In this case, your syntax is slightly incorrect. It should be (note the single quotes):
count_letter('a', 'bananana')
Please have a look below:
a = 5
print a + b
b = 4
When I try to run the code above, it gives an error:
Traceback (most recent call last):
File "C:/Users/user/Documents/modules/ab.py", line 2, in
print a + b
NameError: name 'b' is not defined
Ok. a + b is called before b is defined. That means Python runs the code in order, starts from top to down.
But, how about this one:
class Data:
def __init__(self):
self.debug_level = 9
self.assign = [0, 0, 0, 0]
self.days = 0
def create_days(self, startTime, endTime):
res = 0
try:
if self.final_days < self.maximum_days:
Above, self.final_days and self.maximum_days are not defined yet either, but it does not give any errors. What is the logic behind it?
Best regards,
You're not actually "running" the code yet. In your example, all you have is a method declaration inside the Data class. In it, Python will not check for the existence of class fields because they may be set at another time, in some other method (Python's classes are malleable in that sense).
If you try to run your create_days method in a new instance of the Data class without setting the values for those fields beforehand, you'll get an error.
It doesn't give any errors because the attributes are not accessed when the class is defined. As soon as you call create_days() you'll have a problem :D
The body of a function is evaluated only when it is called, not when it is defined.
References are only looked up when the code is run. You can put whatever names you like in the create_days() method, and none will be checked until the line containing them is executed.
If you actually executed it, you would get
AttributeError: Data instance has no attribute 'final_days'
To reproduce this:
x = Data()
x.create_days(1,2)
also, you have a try block. I assume this is an excerpt from some other code. The try block is probably swallowing the exception.
Python is an interpreted language, unlike c++ it is not compiled so the body of a function isn't evaluated until it is called.