DEV Community

loading...

Discussion on: Advanced Python: for more attractive code

Collapse
mx profile image
Maxime Moreau

Hi, thanks for sharing :)

"else statement also be used after for loop, it is executed after for loop", but why it could be needed? Just put some code after the for loop do the job, nop?

Collapse
teosoft7 profile image
Taeho Jeon Author

Hi, you're welcome.

else: after for loop confirms the for loop is finished, not confirms the exit of the loop.

else: does not be executed when it is exited by 'break' statement.

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! :)