Home > Back-end >  How to exit a while loop nested in a for loop
How to exit a while loop nested in a for loop

Time:12-28

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?

CodePudding user response:

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
  • Related