pythonfor-loopfor-else

How else part work in continue statement?


I'm not sure how the continue statement is interpreted when it is inside a for loop with an else clause.

If the condition is true, the break will exit from a for loop and else part will not be executed. And if the condition is False then else part will be executed.

But, what about continue statement? I tested it seems that the after the continue statement is reached, the else part will be executed. Is this true?? Here is a code example:

# when condition found and it's `true` then `else` part is executing :

edibles = ["ham", "spam", "eggs","nuts"]
for food in edibles:
    if food == "spam":
        print("No more spam please!")
        continue
    print("Great, delicious " + food)

else:
    print("I am so glad: No spam!")
print("Finally, I finished stuffing myself")`

If I remove "spam" from the list, now the condition is always false and never found but still the else part is executed:

edibles = ["ham","eggs","nuts"]
for food in edibles:
    if food == "spam":
        print("No more spam please!")
        continue
    print("Great, delicious " + food)

else:
    print("I am so glad: No spam!")
print("Finally, I finished stuffing myself")

Solution

  • Your else part will be executed in both cases. else part executed when loop terminate when condition didn't found.Which is what is happening in your code. But it will also work same without continue statement.

    now what about break statement's else part, Break statement's else part will be executed only if:

    enter image description here