I was attempting to make a game using Pygame, when implementing a function where the character shoots a projectile on the space bar being pressed, I came across an error:
File "/File/Path/Game.py", line 58 in draw_window
for block_bullet in block_bullet:
File "/File/Path/Game.py", line 123, in <module>
draw_window()
UnboundLocalError: local variable 'block_bullet' referenced before assignment
I have viewed other questions attempting to find an answer but could not find a solution
Here is a google docs link to the code:
https://docs.google.com/document/d/1YPIv3hIKtbTSORd_e4yRCCP9gIo_tJL6kzhIQHiodLI/edit?usp=sharing
I would like the 'Blocky' character to shoot these 'block_bullets' when the spacebar is pressed
In Python, any attempt to modify a variable within a function results in that variable being local to the function. In your draw_window function, the line of code for block_bullet in block_bullet: attempts to modify the block_bullet variable, which has the effect of referencing a local variable to which no value is assigned, producing that error.
You need to rename the first use of block_bullet in that function to some other name, resulting in the code for individual_bullet in block_bullet: indivdual_bullet.draw(win). (Any name that is not already used elsewhere in your program could work to replace individual_bullet in my example.)
Related
How interpreter of Python recognize undefined global variable (a) in function in the following code ?
def show():
print(a)
a = 1
show()
Python is interactive language, so it processes each line of code line by line.
Given this, it should throw an error at the line with undefined variable (print(a)).
However, it works without error.
How does interpreter of Python recognize the undefined variable (a) ?
Or is it just recognized as letters until show function is called?
I converted the above code to bytecode, but I didn't understand well it...
When you define your function inside a python interpreter, python treats it as a sort of black box. It initializes the variables that are not defined inside and outside the function as free variables. Then, it stores a reference to the function inside the global table (you can access it using globals()). This global table holds the values for global variables and global function references.
When you define the variable a python stores it inside the global dictionary as well. Just like the function before it.
After that when you call your function, python sees a variable a. It knows that the variable is free, therefore, must be declared inside the global variable by now. Then it looks up the global table and uses the value that is stored.
Python is run line by line, and in saying that, it will skip over the function until the function is called. So even though it's line by line, it's still running afterwards.
Use of global keyword:
To access a global variable inside a function, there is no need to use global keyword. As a is not assigned inside the function, python will look at the global scope.
We use global keyword to assign a new value to the global variable.
This example throws an error -
def show():
a = a + 5
print(a)
a = 1
show()
Error:
UnboundLocalError: local variable 'a' referenced before assignment
As far as I understand variables initialised inside if statments are scoped to the function but the following code is throwing up UnboundLocalError: local variable 'seq_name' referenced before assignment errors
def scraper(filename):
if 'Identified secondary metabolite regions using strictness' in line:
seq_name = readfile[i + 1].split('_')[0]
if seq_name in line
I have shortend the code to contain only the relavent bits. I am unsure how to fix this error given that my understanding is correct. Please correct me if it is not.
Your understanding of scope is correct. Variables initialized inside if blocks are scoped to the enclosing function.
However, it's still possible (as is happening here) to skip the condition in which you assign the variable, and thus never have assigned it at all. UnboundLocalError: local variable 'seq_name' referenced before assignment is the error message for whenever a variable hasn't been assigned in the current scope yet, even when it could have been. You have to account for that possibility in your code - an else clause is the easiest way to do that.
I am working to create a quiz on Python with different difficulty levels. I am trying to use functions so I can keep calling the most frequent part of the code, appending the questions into a list from an external text file.
However, I am running into a problem. When attempting to call my function I get the error:
NameError: name 'f' is not defined
I've tried everything I can think of but if anyone could provide any help, it would be greatly appreciated!
Here is the function:
def quiz(f):
f = open("quiz.txt", "r").read().split('\n')
for line in f:
f.append(questions)
f.close()
quiz(f)
print(questions)
The print(questions) bit is just a way for me to check if the lines have appended to the list.
When your code hits the line quiz(f), no f has been defined.
At that point in your code, only one thing has happened -- a function name quiz has been defined. That's the only identifier you can refer to at that point in your code.
You have declared function quiz to accept a parameter, but it makes no use of that parameter. The correct definition would be def quiz().
Whenever I start my game and let's say for example I enter 1,4 as the grid reference it will reply with
"UnboundLocalError: local variable 'of' referenced before assignment"
How can I fix this?
Code (edited to for brevity):
import time
while 1==1:
cont=1
while cont==1:
of="-"
tf="-"
rf="-"
ov="-"
tv="-"
rv="-"
os="-"
ts="-"
rs="-"
go=1
...
Variable of (and all the other 2-letter variables) are not available in function xturn.
I strongly recommend that you use incremental programming: write a few lines of code, get those working, and then enlarge your program. This allows you to zero in on errors quite easily. Any time I attack a new style of programming, I find this quite useful. It appears that you're new to some of the techniques you're using here.
For instance, you're using in instead of == for comparisons. This is not going to work well as a general principle.
Declare your functions before the main program. The way you wrote this, you're redefining your functions every time you go through the loop. Moving functions to the top will cure you of many variable scoping problems, too.
Learn to use Boolean values and variables. Your loops should look like this:
while True:
cont = True
while cont:
You make variables available by passing them as arguments to the function. I can see that you're new to this, because you've given this function a parameter x that you never use.
Overall, you should not have 9 variables: you should have a list, and then just pass the entire list as the current state of the game board. If you number the squares 0-8, you can easily work with the board in that respect.
To solve the immediate problem, you can add this line to each of your routines:
global of,tf,rf,ov,tv,rv,os,ts,rs
This will make the variables available. I see that #Thomas has pointed this out.
Still, I encourage you to work on designing this more cleanly. Using global variables is generally bad design. Also, notice how much code you have to duplicate for this program? It should be a lot easier.
Accessing a variable inside one of your functions will basically work even if the variable is defined only in an outside scope. But in your xturn function, you have a line that assigns to of. It doesn't matter whether this line has been executed before the error occurs; its mere existence anywhere inside the function causes the Python interpreter to treat it as a local variable. Therefore, when accessing it in the if clause, Python tries to access a local variable of and now it does matter that such a local variable hasn't been assigned up until that point.
In your function xturn you use the variable of which is not declared / known in that scope, thus the error.
If you look at the stack trace:
Traceback (most recent call last):
File "D:/Projekte/Python/snakes35/blabla.py", line 141, in <module>
ocheck(1)
File "D:/Projekte/Python/snakes35/blabla.py", line 138, in ocheck
xturn(1)
File "D:/Projekte/Python/snakes35/blabla.py", line 33, in xturn
if goo in "1,4" and of not in "o":
UnboundLocalError: local variable 'of' referenced before assignment
you can figure that out via looking at the lines in your file, where the error ocures.
I am completely stumped. I looked at other answers to this same question, but none seemed to give the slightest answer as to why I myself am getting this error. I have pretty much 2 of the exact same programs running the same code with the exception of some URL's and Product ID's that it reads from files. The programs are a little bit long, so I put them on Pastebin Here. I don't expect you to read all the code, the error occurs in the main function where I define PID and then try to use it later in the function. Why does one work perfectly fine and the other does not? As far as I can see they are the same in that part, but maybe I missed something! Any help is appreciated!
Thanks!
PS: The error I receive is:
UnboundLocalError: Local variable 'PID' referenced before assignment
Your findall('CRC-START(.*?)CRC-END', PIDFile.read(), re.S) on line 202 didn't find anything, PID didn't get declared, boom, UnboundLocalError.
This happens because python interpreter makes a preliminary pass on the code, marking encountered variables as local, but it does not (and cannot) check if code that declares them will actually be executed.
Minimal reproducible example of that effect would be this:
>>> def foo():
if 0:
a = 1
print a
>>> foo()
Traceback (most recent call last):
File "<pyshell#5>", line 1, in <module>
foo()
File "<pyshell#4>", line 4, in foo
print a
UnboundLocalError: local variable 'a' referenced before assignment
(Rep not high enough to 'comment') Link doesn't work. Could you maybe provide the code excerpt?
This error occurs when you try to use a variable before it is initialized (or defined depending on your code) - when you try to use a variable outside of its scope. Make sure that your variable WILL be initialized by the reference point. I'm wondering if you put that in an if-statement that doesn't get entered...
First of all, it seems that you reassign a new list to PID every iteration of a for loop. In the end your PID will contain only the last result.
I think what you really want to do is assign an empty list to PID before the for loop. Maybe after output = open(outputFile, 'w') and then append results to PID every iteration. Then you will not get UnboundLocalError even if nothing is found in PID.txt.