python : local variable referenced before assignment error

标签 python boids

一直报错

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/

相关文章:

java - 修改另一个类中的 ArrayList 对象值

c++ - 物体相互碰撞

python - 在实体模拟中定义速度

python - 自定义列表遍历和修改

python - `np.any` 从对象数组返回一个对象而不是 bool 值?

python - to_sql 的数据透视表

Javafx Canvas 未正确清除。

Python ast.Print "nl"参数?

python - 是否可以部署使用 Python 3.4 和 Fabric 的应用程序?

java - 在 ArrayList 中获取 "size() does not exist"错误