Reputation: 90
When I Run My Python Program it says
"UnboundLocalError: local variable 'isrunning' referenced before assignment". I
Don't Know Why This Happens.
I Don't Even Know Where To Start TTo Fix This Problem.
isrunning = True
def redrawgame():
win.blit(bg, (bgX, 0)) # draws our first bg image
win.blit(bg, (bgX2, 0))
if isrunning == True:
win.blit(Run[imagerun],(x, y))
I Define isrunning
before I use it in redrawgame()
, so IDK why this is happening. Please Help. I just want this error to go away.
Upvotes: 0
Views: 235
Reputation: 211125
When you make an assignment to a variable in a scope, that variable becomes local to that scope.
I assume that you do an assignment to the variable isrunning
in the scope of redrawgame
. e.g.:
def redrawgame():
# [...]
isrunning = False
Since isrunning
is local in the scope of redrawgame
, the statement
if isrunning == True:
tries to read this local variable, which is not defined at this point. This cases the error:
"UnboundLocalError: local variable 'isrunning' referenced before assignment".
See also Why am I getting an UnboundLocalError when the variable has a value?
To write to a variable in global namespace in the scope of a function you've to use the global
statement:
isrunning = True
def redrawgame():
global isrunning
win.blit(bg, (bgX, 0)) # draws our first bg image
win.blit(bg, (bgX2, 0))
if isrunning == True:
win.blit(Run[imagerun],(x, y))
# [...]
isrunning = False
Now the value is read form the variable in global name space and there is no more local variable with the same name.
Upvotes: 1