Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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")
like image 572
Jona Avatar asked Jul 14 '16 18:07

Jona


People also ask

How does Python know when a for loop ends?

The for loop ends at the line where the indentation drops back to the same level or lower as the for statement.

How do I check if a loop is broken in Python?

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.

How do you check for loops in Python?

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 .


2 Answers

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")
like image 123
Moses Koledoye Avatar answered Sep 27 '22 17:09

Moses Koledoye


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")
like image 32
Abhijit Avatar answered Sep 27 '22 18:09

Abhijit