'I am confused about these python errors [duplicate]
So, I am developing this game where the graphics is made entirely of text.
This prototype looks right but there are some errors in the program.
If anyone has any solutions to the problem please, tell me.
global tiles
tiles = ["=","#"," "]
st1 = [1,1,1,1,1]
global pcx
global pcy
global lcx
global lcy
pcx = 3
pcy = 3
lcx = 3
lcy = 3
#makes 1 charecter on the screen
def j1t(ps):
ltr = ""
if pcx == lcx and lcy == pcy: # error "UnboundLocalError: local variable 'pcx' referenced before assignment""
ltr = "@"
else:
ltr = tiles[ps[pcx]]
if pcx == 5:
pcx -= 4
else:
pcx += 1
return ltr
print(j1t(st1)) # error "line 25, in <module> print(j1t(st1))"
Solution 1:[1]
Functions do not see global variables by default. You have to use the global statement inside a function to tell it to see the global variable. Otherwise, any reference to that variable is actually an attempt to reference a function local variable by that name. And since you don't have a variable called pcx inside that function, you get the UnboundLocalError.
Add global to the beginning of your function as below, so that it can access the global variables.
def j1t(ps):
global pcx, pcy, lcx, lcy # Add this line
ltr = ""
if pcx == lcx and lcy == pcy:
ltr = "@"
else:
ltr = tiles[ps[pcx]]
if pcx == 5:
pcx -= 4
else:
pcx += 1
return ltr
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 |
