0

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(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))
print rho
print m

etc., give correct results.

Any suggestion is welcome and appreciated.

5
  • 3
    This might be a pasting error, but in the function N is not defined. Commented Aug 26, 2011 at 19:41
  • 1
    @Chris Pickett not having N defined would throw an Exception ...though it would be good to know that it wasn't set to 0 Commented Aug 26, 2011 at 19:44
  • Exactly, not knowing N, it's hard to diagnose. Commented Aug 26, 2011 at 19:45
  • 1
    Whatever the problem is, it's not the for- loop. Commented Aug 26, 2011 at 20:25
  • 3
    We don't have enough information to help you solve your problem. Please devise a minimal example that demonstrates the problem and post the whole module. Commented Aug 26, 2011 at 20:32

2 Answers 2

1

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.

Sign up to request clarification or add additional context in comments.

Comments

0

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.