Iterating within a function using for loop doesn't work?
When I use for loop within a function (see below), the block of statements below the for loop is not iterated,
def F(rho, m, E, v_rho, v_m, v_E):
for n in xrange(N):
#Update conserved quantities
rho = G(Evolve_rho1(rho))
m = momentum(Evolve_m1(m))
E = Energy(Evolve_E1(E))
v_rho = rho_v(Evolve_rho_v(rho))
v_m = m_v(Evolve_mv(m))
v_E = E_v(Evolve_Ev(E))
return (rho, m, E, v_rho, v_m, v_E)
since after calling the function in this way: density, momentum, Energy, dflux, mflux, Eflux = F(rho, m, E, v_rho, v_m, v_E)
, and
print for example density, leads to wrong answer.
But if I only use for loop like below, it works fine.
for n in xrange(N):
#Update conserved quantities
rho = G(Evo开发者_Go百科lve_rho1(rho))
m = momentum(Evolve_m1(m))
E = Energy(Evolve_E1(E))
v_rho = rho_v(Evolve_rho_v(rho))
v_m = m_v(Evolve_mv(m))
v_E = E_v(Evolve_Ev(E))
print rho
print m
etc., give correct results.
Any suggestion is welcome and appreciated.
I'm guessing your missing the difference between a global and a local vlue for N
. As you've written it, the value of N
in the F
function will be whatever N is when F
is called, not when it's defined. So if at the time F
is called N==0
, then the loop block will never be executed.
The function was using global variables instead of local which were updated in each iteration in F(). The solution is to pass variables as parameters and define `
def F(rho, m, E, v_rho, v_m, v_E):
for n in xrange(N):
rho = G(Evolve_rho1(rho,v_rho,m))
m = momentum(Evolve_m1(rho,v_rho, m,v_m,E))
E = Energy(Evolve_E1(rho, m, E, v_E))
v_rho = rho_v(Evolve_rho_v(rho,v_rho,m))
v_m = m_v( Evolve_mv(rho,v_rho, m,v_m,E))
v_E = E_v(Evolve_Ev(rho, m, E, v_E))
return (rho, m, E, v_rho, v_m, v_E)
Thanks Folks for all your contributions.
精彩评论