22

This is a ceased for loop :

for i in [1,2,3]:
    print(i)
    if i==3:
        break

How can I check its difference with this :

for i in [1,2,3]:
    print(i)

This is an idea :

IsBroken=False
for i in [1,2,3]:
    print(i)
    if i==3:
        IsBroken=True
        break
if IsBroken==True:
    print("for loop was broken")
Jona
  • 629
  • 1
  • 6
  • 16
  • I think your idea is the best. The else clause in python is only run when the for loop does not break. So detecting a break is probably best done as you suggest. Go ahead and put that in your own answer if nothing better comes up. – rkh Jul 14 '16 at 18:47

2 Answers2

51

for loops can take an else block which can serve this purpose:

for i in [1,2,3]:
    print(i)
    if i==3:
        break
else:
    print("for loop was not broken")
Moses Koledoye
  • 77,341
  • 8
  • 133
  • 139
11

Python for loop has a else clause that is called iff the loop ends.

So, this would mean something in line

for i in [1,2,3]:
    print(i)
    if i==3:
        break
else:
    print("Loop Ended without break")

If instead you need to handle both the scenario, using exception for sequence control is also a viable alternative

try:
    for i in [1,2,3]:
        print(i)
        if i==3:
            raise StopIteration
except StopIteration:
    print ("Loop was broken")
else:
    print ("Loop was not broken")
Abhijit
  • 62,056
  • 18
  • 131
  • 204