Search code examples
pythonpython-2.7vpython

UnboundLocalError: local variable 'p' referenced before assignment


def partial(f,h=0.0001):
    #checker
    x=y=z=1
    fx=(f(x+h,y,z)-f(x,y,z))/h
    fy=(f(x,y+h,z)-f(x,y,z))/h
    fz=(f(x,y,z+h)-f(x,y,z))/h
    if(fx==0):
        p=0
    elif(fy==0):
        q=0
    elif(fz==0):
        r=0
    fx=fy=fz=0
    a=15
    c=5
    for m in range (-a,a,c):
        for n in range (-a,a,c):
            for o in range (-a,a,c):
                x=m
                y=n
                z=o
                if(p==0):
                    x=0
                elif(q==0):
                    y=0
                elif(r==0):
                    z=0
                fx=(f(x+h,y,z)-f(x,y,z))/h
                fy=(f(x,y+h,z)-f(x,y,z))/h
                fz=(f(x,y,z+h)-f(x,y,z))/h
                arrow(pos=vector(m,n,o),axis=vector(+fx,+fy,+fz),color=color.red)
                print z
    print fx,fy,fz
    return 0

Where am I going wrong? I have declared p before, but it says p is referenced before assignment.


Solution

  • You potentially use p, q, and r in your for loop in if/elif statements. That means that these have to be defined, or else you run the risk of the "UnboundLocalError: local variable '_' referenced before assignment" error popping for any of them. However, you only define one of these when you call the function depending on what fx, fy, and fz is).

    The easiest solution is to just add this line:

    p = q = r = -1

    above your if statements setting one of them to 0. (around line 6)

    Now, they'll all be defined and you can reference them inside your for loops regardless of which one gets set to 0.