Back

Explore Courses Blog Tutorials Interview Questions
0 votes
2 views
in Python by (47.6k points)

I understand how this construct works:

for i in range(10):

print(i)

if i == 9:

print("Too big - I'm giving up!")

break;

else:

print("Completed successfully")

But I don't understand why else is used as the keyword here since it suggests the code in question only runs if the for block does not complete, which is the opposite of what it does! No matter how I think about it, my brain can't progress seamlessly from the for a statement to the else block. To me, continue or continuewith would make more sense (and I'm trying to train myself to read it as such).

I'm wondering how Python coders read this construct in their head (or aloud, if you like). Perhaps I'm missing something that would make such code blocks more easily decipherable?

1 Answer

0 votes
by (106k points)

The common reason for using ‘else’ after for or while is to construct the loop to run until something is found and then to break out of the loop. 

Below is an example that is using the Python for...else combination:-

for i in mylist:

if i == theflag:

break

process(i)

else:

raise ValueError("List argument missing terminal flag.")

Browse Categories

...