0

I am working through an example Python script from the book "Doing Math with Python" and I keep running up against a NameError which tells me my variable isn't defined, when, it looks to me like it is defined.

I'm using Python 3.4 and the code is

 '''
    Gravitational Calculations
    '''

    import matplotlib.pyplot as plt

    #Draw the graph

    def draw_graph(x,y):
        plt.plot(x,y,marker='o')
        plt.xlabel('Distance (m)')
        plt.ylabel('Force (N)')
        plt.title("Gravitational force as a function of distance")

    def generate_F_r():
        #Generate values for r
        r=range(100,1001,50)

        #Empty list to store F values
        F=[]

    #G Constant
    G=6.674*(10**-11)
    #Two masses
    m1=0.5
    m2=1.5

    #Calculate F and append it into the F-list
    for dist in r:
        force=G*m1*m2/(dist**2)
        F.append(force)

    #Call the Draw Plot Function
    draw_graph(r,F)

    if __name__=='__main__':
        generate_F_r()

The error it gives me is: NameError name 'r' is not defined

Isn't it defined in the line that states r=range(100,1001,50)?

Why isn't it taking this as a definition?

I'm sure there is something glaringly simple and incredibly stupid I'm doing but I am at my wits end as to how such a simple thing could be so hard.

Thanks!

  • What code should be in `def generate_F_r():`. Because as is, the error is valid. `r` only exists within the `generate_F_r` method. And from how your code is currently structured, you are trying to use it outside the method. – idjaw Mar 29 '16 at 01:57
  • In addition, either your indentation is wrong, or r is used before generate_F_r() is called – Natecat Mar 29 '16 at 01:59

1 Answers1

0

Code in functions is not executed until the function is called. You don't call generate_Fr() until after you have already tried to reference r. Even if you did call the function first, though, r is still just a local variable. You need to make it global with global r at the beginning of the function.

zondo
  • 19,901
  • 8
  • 44
  • 83