Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to exit a while loop nested in a for loop

I guess this should be simple. The first part of the code is to initialize the variables. My problem is with the while loop. If the condition j == len(time) is achieved, I need to exit the WHILE loop and the FOR loop. But the thing is that once the condition is true, the while loop iterates once again; therefore, time is out of index.

import numpy as np

# Variables to initialize the problem
timeframe = 25
dt=0.025
dat=[(0, 5)]
dat.append((timeframe,dat[len(dat)-1][-1]))
time = np.arange(dat[0][0],dat[-1][0]+dt,dt)   
dat_discretized = np.zeros(len(time)) 

#While inside a for loop
j=0
for i in range(len(dat)):
    while   dat[i][0] <= time[j] <= dat[i+1][0]:
       dat_discretized[j] = dat[i][1] 
       j += 1
       print(j)
       if j == len(time):
           break

How can I exist the while loop without rechecking the while condition?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

for i in range(len(dat)):
    breakFor=false
    while   dat[i][0] <= time[j] <= dat[i+1][0]:
       dat_discretized[j] = dat[i][1] 
       j += 1
       print(j)
       if j == len(time):
           breakFor=true
           break
    if breakFor:
        break
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading