帮助解决 Python UnboundLocalError:在赋值前引用了局部变量

3 投票
5 回答
52874 浏览
提问于 2025-04-15 16:01

我之前问过类似的问题,不过我觉得我可能没问清楚。所以我想把我的原始代码贴在这里,希望有人能帮我,我现在真的卡住了……非常感谢。

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

有没有人能给我一些建议?谢谢……

5 个回答

1

在每个 def 语句后面加一个额外的 global 声明,把你所有的全局变量都放进去。否则,如果不这样做,所有的全局变量在你的 def 里面就会变成局部变量。

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

在这段代码中,你在哪里调用了 force 呢?

无论如何,问题出在 update_r 函数里。你在 update_r 的第一行提到了 vs,但在这个函数里并没有定义 vs。Python 不会去看上面定义的 vs。你可以尝试在 update_r 的第一行加上

global vs

或者把 vs 加到 update_r 的参数列表里。

5

update_r的第一行,你有一行代码是vs,ve=update_v(n,vs,ve,ms,me,dt,fs,fe)。看看你调用的这个函数。你在用一堆参数去调用update_v。其中一个参数是vs。但是在这个函数里,vs是第一次出现。也就是说,vs这个变量还没有被赋值。你可以先给它一个初始值,这样你的错误就应该消失了。

撰写回答