一直报错
UnboundLocalError: local variable 'new_speedDx' referenced before assignment
尝试运行以下函数时:
def new_speedD(boid1):
bposx = boid1[0]
if bposx < WALL:
new_speedDx = WALL_FORCE
elif bposx > WIDTH - WALL:
new_speedDx = -WALL_FORCE
bposy = boid1[1]
if bposy < WALL:
new_speedDy = WALL_FORCE
elif bposx > WIDTH - WALL:
new_speedDy = -WALL_FORCE
return new_speedDx, new_speedDy
在这个函数中,boid1 是一个有 4 个元素(xpos、ypos、xvelocity、yvelocity)的向量,所有大写的变量都是常量(数字)。 任何人都知道如何解决这个问题?我在互联网上找到了很多可能的解决方案,但似乎没有任何效果。
最佳答案
必须有可能 bposx 既不小于 WALL 也不大于 WIDTH - WALL。
例如:
bposx = 10
WALL = 9
WIDTH = 200
if bposx < WALL: # 10 is greater than 9, does not define new_speedDx
new_speedDx = WALL_FORCE
elif bposx > WIDTH - WALL: # 10 is less than (200 - 9), does not define new_speedDx
new_speedDx = -WALL_FORCE
如果没有看到程序的其余部分,很难提出合理的回退值,但您可能希望添加如下内容:
else:
new_speedDx = 0
关于 python : local variable referenced before assignment error,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15507179/