我总是犯错误
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既不小于墙,也不大于墙宽。在
例如:
如果不查看程序的其他部分,很难建议合理的回退值,但您可能希望添加以下内容:
^{pr2}$解释
正如其他人所指出的,您所处理的不是
WALL <= pos <= WIDTH - WALL
。在建议变更
如果boid没有撞到墙,它可能会继续以当前的速度前进。其他的程序可以在boid没有撞到墙的情况下将速度设置为0。这个解决方案在使用现有速度方面是与众不同的。我认为这对你的处境很重要。在
代码
有些人认为这个代码很难理解。以下是简要说明:
这是一个general question on the ternary operator。记得吗,心想,“这是一些Python不喜欢的。”
如果你不使用这个代码
返回原稿并修复
yvelocity
大小写中的错误:bposx > WIDTH - WALL
。yvelocity
不依赖于xpos
。在如果这两个条件都不成立,会发生什么?在
。。。
new_speedDx
从未赋值,因此其值不确定。在在这种情况下,可以通过指定
^{pr2}$new_speedDx
应该是什么来缓解这种情况:相关问题 更多 >
编程相关推荐