[英]How to fix Python error : “UnboundLocalError: local variable 'id1' referenced before assignment”
I am trying to create a little game with python. 我正在尝试用python创建一个小游戏。 I have made this code : 我已经编写了此代码:
def create_ennemy() :
x = 1200
y = randint(0, 650)
t = randint(1, 5)
if t <= 4 :
id1 = c.create_polygon(7.5, 7.5, 7.5, 37.5, 52.5, 22.5, fill='red')
r = 22.5
elif t == 5 :
c.create_polygon(7.5, 7.5, 7.5, 75, 105, 45, fill='red')
r = 45
ennemy_list.append(id1)
ennemy_type.append(t)
But I get the following error : 但是我收到以下错误:
File "Jeux-d-avions.py", line 71, in create_ennemy ennemy_list.append(id1) UnboundLocalError: local variable 'id1' referenced before assignment create_ennemy ennemy_list.append(id1)中的文件“ Jeux-d-avions.py”,行71,UnboundLocalError:分配前已引用本地变量“ id1”
I searched on the internet but it did not solve my problem. 我在互联网上搜索,但是并不能解决我的问题。 Why my code is not working? 为什么我的代码无法正常工作?
In your code, there is no assignment of id1
in the case of elif
在您的代码中,如果是elif
,则不会分配id1
I guess what you mean should be as follows: 我想你的意思应该如下:
def create_ennemy() :
x = 1200
y = randint(0, 650)
t = randint(1, 5)
if t <= 4 :
id1 = c.create_polygon(7.5, 7.5, 7.5, 37.5, 52.5, 22.5, fill='red')
r = 22.5
elif t == 5 :
id1 = c.create_polygon(7.5, 7.5, 7.5, 75, 105, 45, fill='red')
r = 45
ennemy_list.append(id1)
ennemy_type.append(t)
There is no issue in your code, you just need to indent your code and a minor change to assign id1
. 您的代码没有问题,您只需要缩进您的代码,并进行较小的更改即可分配id1
。
def create_ennemy() :
x = 1200
y = randint(0, 650)
t = randint(1, 5)
if t <= 4 :
id1 = c.create_polygon(7.5, 7.5, 7.5, 37.5, 52.5, 22.5, fill='red')
r = 22.5
elif t == 5 :
id1 = c.create_polygon(7.5, 7.5, 7.5, 75, 105, 45, fill='red')
r = 45
ennemy_list.append(id1)
ennemy_type.append(t)
this will fix you mentioned error. 这将解决您提到的错误。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.