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")
The for loop ends at the line where the indentation drops back to the same level or lower as the for statement.
In python, you can use the for/else statement. You can add an else statement after a for loop and if break was not called, the else statement will trigger.
You can iterate the list with shifted versions of itself via zip . For each triplet, test your two conditions. Use next to extract such triplets; if no such triplet exists, you will meet StopIteration error. Never name a variable after a built-in, e.g. use lst instead of list .
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")
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")
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With