Search code examples
pythonfor-loopcontinue

How to find the iteration in which the continue-sattement takes place in python


I have a for loop and a continue statement in it in python. I want to know the number of iteration in which the continue statement took place. I mean:

count=0
for i in range (5):
    if i == 3:
        count+=1
        continue
    print (i)

The count value tells me that 1 time I have faced the continue in my for loop. But I want to know in which iteration was it, which obviously is the fourth iteration (after printing 0, 1 and 2). In reality I may get into continue several time and this is only a simple example to clarify my proble. I do appreciate if anyone let me know how to find it out. In advance, thanks for any help.


Solution

  • Each time continue is run, add the current index to count. At the end the count list will contain all the indexes in which continue has been executed. The length of count will tell you how many times continue has been run.

     if __name__ == '__main__':
            count = []
            for i in range(5):
                if i == 3:
                    count.append(i+1) #because iter starts with 0
                    continue
                print(i)
        print(count)
        print(len(count))
    

    Clarification

    You can change i+1 with i, it depends on how you want to interpret it. In general it depends on whether you want to take into account that the iteration started from 0 or not.