Jona Jona - 4 months ago 8
Python Question

How to check whether for loop ends completely in python?

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")

Answer

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")
Comments