0

I'm trying to use main function in order to make the trajectory of the projectile with air resistance. The problem is, when I'm using main function, I got an error but not when I use function without main, what I did it wrong?

    v=float(input("initial velocity: "))
    theta=float(input("Angle from the horizontal of initial velocity: "))
    B=float(input("normalised drag coefficient: "))
    t=float(input("the step interval in seconds: " ))

    vx = v * math.cos(theta*math.pi/180.0)
    print(str(vx))
    vy = v * math.sin(theta*math.pi/180.0)
    sx = 0
    sy = 0
    t0 = 0
    ax = 0
    ay = 0
    g= 9.81

    def AX(ax):
        ax= -B*v*vx
        return ax
    def AY(ay):
        ay= -(B*v*vy)-g
        return ay
    def VX(vx):
        vx=vx+ax*t
        return vx
    def VY(vy):
        vy=vy+ay*t
        return vy
    def SX(sx):
        sx= sx + vx*t
        return sx
    def SY(sy):
        sy= sy + vy*t
        return sy
    Xdisplacement=[]
    Ydisplacement=[]
    def main():
        while sy>=0 :
            Xdisplacement.append(float(sx))
            Ydisplacement.append(float(sy))
            sx=SX(sx)
            sy=SY(sy)
            ax=AX(ax)
            ay=AY(ay)
            vx=VX(vx)
            vy=VY(vy)
            v= ((vx**2.0)+(vy**2.0))**(1.0/2.0)

        plt.plot(Xdisplacement,Ydisplacement)
        plt.title("trajectory")
        plt.xlabel("x")
        plt.ylabel("y")
        plt.show()
    main()
Nai
  • 3
  • 2
  • Why did you start indenting the code at the `vx = ...` line? – Barmar Oct 30 '16 at 00:46
  • What error did you get? – Barmar Oct 30 '16 at 00:46
  • I'm sorry. It was the problem when I copied the code and post. Speaking of which, if I don't put main() everything works fine. But if I put main() like this, I got "UnboundLocalError: local variable 'sy' referenced before assignment" – Nai Oct 30 '16 at 08:30
  • The problem is that within the scope of the `main` function you are making a reference to `sy` before you assign it. Depending on what behavior you are after, you may want to initialize it to zero within your main function. – kabdulla Oct 30 '16 at 10:59

1 Answers1

0

If you insist on using global variables and don't want to explicitly send them to a function you have to explicitly define them as global:

def main():
    global sy,sx,ax,ay,vx,vy

and then the rest. You may have seen answers this is unnecessary for read operations on global variables (as in your while sy >= 0) but python will assume the variable is local if you assign to it anywhere within the function, and you do. Hence, as a local variable it is not defined at the start of the while.

kabanus
  • 22,925
  • 6
  • 32
  • 68
  • I have added the global variable in main function (including v) and it works now. And thank you for the advice. – Nai Oct 31 '16 at 13:52