For else statement usage and meaning

260 Views Asked by At

I came across some code that has the structure:

for val in list:
   do_something(val)
   if val is x:
       break
else:
   do_something_else()

I couldn't find much information about this structure except that the else block won't be executed unless the for loop both executes, and finishes executing without hitting the break.

What would this be used for?

Is there a reason for it not being named something like 'finally', since that would seem to make more logical sense?

Thanks.

1

There are 1 best solutions below

0
On

Look on this question Else clause on Python while statement In two words this construction can be used for cases, when you need to do something after a loop, but you don't want to it it if loop was broken (by break statement). That's why it is not like 'finally' which are being executed in ANY case.