Python脚本中的NameError

时间:2016-03-29 01:56:27

标签: python

我正在使用“使用Python做数学”一书中的示例Python脚本,并且我继续遇到一个NameError,它告诉我我的变量没有定义,何时,它看起来像我定义的那样。 / p>

我使用的是Python 3.4,代码是

 '''
    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()

它给我的错误是: NameError名称'r'未定义

是否在r = range(100,1001,50)的行中定义了?

为什么不将此作为定义?

我确信我正在做一些非常简单和令人难以置信的愚蠢事情,但我最终知道这么简单的事情会如此困难。

谢谢!

1 个答案:

答案 0 :(得分:0)

函数中的代码在调用函数之前不会执行。在您尝试引用generate_Fr()之后,才能致电r。即使你 首先调用该函数,r仍然只是一个局部变量。您需要在函数开头使用global r将其设为全局。

相关问题