Python UnboundLocalError帮助:赋值前引用的局部变量

时间:2009-11-14 19:13:43

标签: python numpy

我之前发过类似的问题,但是,我想我可能误解了我的问题,所以我可以在这里发布我的原始代码,寻找有人可以帮助我,我现在真的被困了......谢谢很多。

from numpy import *
import math as M

#initial condition  All in SI unit
G=6.673*10**-11   #Gravitational constant
ms=1.9889*10**30 #mass of the sun
me=5.9742*10**24 #mass of the earth
dt=10           #time step
#Creat arrays
vs=array([[0,0,0]])     #1st element stand for x component of V of earth
ve=array([[29770,0,0]])
rs=array([[0,0,0]])           
re=array([[0,1.4960*10**11,0]])

#First update velocity in order to start leapfrog approximation
fs=-G*ms*me*((rs-re)/(M.sqrt((rs-re)[0][0]**2+(rs-re)[0][1]**2+(rs-re)[0][2]**2))**3)
fe=-fs
vs=vs+fs*dt/ms 
ve=ve+fe*dt/me

n=input('please enter the number of timestep you want it evolve:')
#update force
def force(n,ms,me,rs,re,G):
    rs,re=update_r(rs,re,n,dt)
    fs=-G*ms*me*((rs-re)/(M.sqrt((rs-re)[0][0]**2+(rs-re)[0][1]**2+(rs-re)[0][2]**2))**3)
    fe=-fs
    return fs,fe

#update velocities
def update_v(n,vs,ve,ms,me,dt,fs,fe):
    fs,fe=force(n,ms,me,rs,re,G)
    i=arange(n)
    vs=vs+fs[:]*i[:,newaxis]*dt/ms
    ve=ve+fe[:]*i[:,newaxis]*dt/me
    return vs,ve

#update position
def update_r(rs,re,n,dt):
    vs,ve=update_v(n,vs,ve,ms,me,dt,fs,fe)
    i=arange(n)
    rs=rs+vs[:]*i[:,newaxis]*dt
    re=re+ve[:]*i[:,newaxis]*dt
    return rs,re
#there is start position,v,r,f all have initial arrays(when n=0).
#then it should calculate f(n=1) then use this to update v(n=0)
#to v(n=1),then use v(n=1) update r(n=0) to r(n=1),then use r(n=1)
#update f(n=1) to f(n=2)....and so on until finish n.but this code seems doesnt do this,,how can I make it? – 

当我调用force python时:

please enter the number of timestep you want it evolve:4Traceback (most recent call last):
  File "<pyshell#391>", line 1, in <module>
    force(n,ms,me,rs,re,G)
  File "/Users/Code.py", line 24, in force
    rs,re=update_r(rs,re,n,dt)
  File "/Users/Code.py", line 39, in update_r
    vs,ve=update_v(n,vs,ve,ms,me,dt,fs,fe)
UnboundLocalError: local variable 'vs' referenced before assignment

任何人都可以给我一些提示吗?谢谢......

4 个答案:

答案 0 :(得分:9)

你在这个代码中将force强行称为什么?

无论如何,问题出在update_r中。您在update_r的第一行中引用vs,即使此函数中未定义vs。 Python没有关注上面定义的vs。尝试添加

global vs

作为update_r的第一行或将update添加到update_r的参数列表

答案 1 :(得分:5)

update_r的第一行,您有vs,ve=update_v(n,vs,ve,ms,me,dt,fs,fe)。查看您正在调用的函数。您正在使用一堆参数调用update_v。其中一个参数是vs。但是,这是该函数中第一次出现vs。变量vs还没有与之关联的值。首先尝试初始化它,你的错误应该消失

答案 2 :(得分:1)

在每个global语句后添加一个包含所有全局变量的def语句。否则,所有全局变量都会转换为你的def中的本地变形而没有它。

def update_v(n,vs,ve,ms,me,dt,fs,fe):
    global vs, ve, ...  

答案 3 :(得分:0)

在第39行,你做

vs,ve=update_v(n,vs,ve,ms,me,dt,fs,fe)

当你在一个功能里面时。 由于您定义了一个名为 vs 全局变量,因此您可以期望这样做。 如果你有:

,它会有用
vs_new,ve_new = update_v(n,vs,ve,ms,me,dt,fs,fe)

因为那时解释器知道函数参数中的 vs 是全局的。但由于您在左侧有 vs ,因此您创建了一个未初始化的本地变量。

但是老兄,你的代码中存在更大的问题: update_r调用update_v,update_v调用force,并强制调用update_r - 你会得到堆栈溢出:)