Breaking out of a mixture of for loops and if conditions

51 views Asked by At

I have a piece of code which has several loops in it. By checking a condition (using an if statement) I want to come out of all the loops except the last one. Is there a way to do it without modifying much of my code as I have very less time to submit it.

for file in dirs:
   ....
   ....
   #Opens a file in the directory
   with open(path, 'rU') as csvfile:

      ....
      ....
      ....
      #Iterates over every row in the File
      for row in csvreader:
          ...
          #If the data is insufficient, the next row will be iterated. 
          if len(Parameters)>15:                       
          #If this condition is not satisfied then I need to go to the next iteration of the first 'for' loop
          #Without Calculating the Average_Slip  
          ....
          ....
          Calculation_of_Slip() 
          #Because when all the rows are done iterating, Average_Slip encounters an error as the input values depend on the Slip.   
          #Instead I need to go to the next file in the directory 
   Average_slip(Slip_3MW,Slip_7MW,Slip_9MW,Counter_1, Counter_2, Counter_3, Counter_4)

I am sure I am missing something very simple but can anyone please help me.

1

There are 1 answers

0
Chop On BEST ANSWER

Based on an answer to a previous similar question: you could refactor your code the nested loops into a function and break it with return.

This will also increase readibility as nested flow control can become a mess if there are too many levels.