DEV Community

loading...

Discussion on: Advanced Python: for more attractive code

Collapse
detinsley1s profile image
Daniel Tinsley

The 'else' is used if the loop completes successfully, so if the loop ends early, such as by using a 'break' statement, the 'else' won't run. It's just an easier way to run code if and only if the loop finishes successfully without needing to use a flag variable to detect whether the loop finishes.

With flag:

flag = True
for i in range(10):
    if i == 8:
        flag = False
if flag:
    print('Loop completed') # won't print, since flag is False

With 'else':

for i in range(10):
    if i == 8:
        break
else:
    print('Loop completed') # won't print since the loop ended early

In both cases, the text won't print, since the loop didn't complete. However, if the loops did complete, then the text would print.

Collapse
mx profile image
Maxime Moreau

Hi, well thank a ton! :)