0

I'm trying to build a list of "populations" based on two ranges and one list. The nested loop I've created doesn't stop, even though I specify where it should break (I've checked the length of the list used in the loop which is equal to 303). So the output is infinite: after it prints the population value for v=2, J=100 (maximum needed), it goes back to displaying v=0,J=0 value for population. How can i fix that? Here is the code:

from scipy.optimize import minimize_scalar
import math
import itertools

we=268.64
wexe=0.814
weye=-0.0017
Be=0.0568325
ae=0.0001969
ge=-0.00000047
De=1.02E-8
kb=1.38065E-23

energy_groundJ=[]
def energyJ (v,J):
    E = we*(v+0.5) + wexe*(v+0.5)**2 + weye*(v+0.5)**3 + Be*(J*(J+1)) - ae*(v+0.5)*(J*(J+1)) - De*(J*(J+1)) + ge*(J*(J+1))*(v+0.5)**2
    E_J=E*1.986E-23
    return E_J
for v in [0,1,2]:
    for J in range(0,101):
        E_J=energyJ(v,J)
        energy_groundJ.append(E_J) 

Population=[]
def population_ground():
    P=(2*J+1)*math.exp(-i/(kb*295))
    return P
for i in energy_groundJ:
    for v in [0,1,2]:
        for J in range(0,101):
            if i==303:
                break
            P=population_ground()
            Population.append(P)
            print("population at v = "+str(v)+" and J ="+str(J)+"  = "+str(P))
Lina
  • 11
  • 2
  • The `break` condition relies on the value `303` being present in `energy_groundJ`. The values you are inserting into `energy_groundJ` are all floating-point numbers. So I doubt the integer 303 is in there. Perhaps your `break` condition should be `i > 303.0` ? – mario_sunny Nov 05 '19 at 17:22
  • `break` only breaks the *innermost* loop. Python does not have a `break – Giacomo Alzetta Nov 05 '19 at 17:22
  • 1
    Possible duplicate of [How to break out of multiple loops?](https://stackoverflow.com/questions/189645/how-to-break-out-of-multiple-loops) – C_Z_ Nov 05 '19 at 17:23
  • @mario_sunny That would still run all the iterations of the loop, but simply avoid running the body. Might be fine but if there are millions of combinations you'll still notice the delay. – Giacomo Alzetta Nov 05 '19 at 17:23

1 Answers1

0

break only breaks you out of one "for" loop (the closest one/top of the stack), not multiple.
Since your other loops don't do anything before the check, you could do this:

for i in energy_groundJ:
    if i==303:
        break
    for v in [0,1,2]:
        for J in range(0,101):
            P=population_ground()
            Population.append(P)
            print("population at v = "+str(v)+" and J ="+str(J)+"  = "+str(P))