Python脚本中的NameError

2024-03-28 11:08:50 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在学习《用Python做数学》一书中的一个Python脚本示例,我不断遇到一个NameError,它告诉我我的变量没有定义,在我看来,它好像已经定义了。你知道吗

我使用的是python3.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(1001,50)的行中定义的吗?你知道吗

为什么不以此为定义?你知道吗

我肯定我在做一些非常简单和愚蠢的事情,但是我真的不知道这么简单的事情怎么会这么难。你知道吗

谢谢!你知道吗


Tags: thefor定义defasrangepltgenerate
1条回答
网友
1楼 · 发布于 2024-03-28 11:08:50

函数中的代码在函数被调用之前不会执行。在尝试引用r之前,不能调用generate_Fr()。即使您先调用了函数,r仍然只是一个局部变量。您需要在函数的开头使用global r使其成为全局函数。你知道吗

相关问题 更多 >