Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why does else behave differently in for/while statements as opposed to if/try statements?

I have recently stumbled over a seeming inconsistency in Python's way of dealing with else clauses in different compound statements. Since Python is so well designed, I'm sure that there is a good explanation, but I can't think of it.

Consider the following:

if condition:
   do_something()
else:
   do_something_else()

Here, do_something_else() is only executed if condition is false, as expected.

Similarly, in

try:
   do_something()
except someException:
   pass:
else:
   do_something_else()
finally:
   cleanup()

do_something_else() is only executed if no exception occurred.

But in for or while loops, an else clause is always executed, whether the contents of the for/while block have been executed or not.

for i in some_iterator:
   print(i)
else:
   print("Iterator is empty!")

will always print "Iterator is empty!", whether I say some_iterator = [] or some_iterator = [1,2,3]. Same behavior in while-else clauses. It seems to me that else behaves more like finally in these cases. What am I overlooking?

like image 702
Tim Pietzcker Avatar asked Oct 16 '09 06:10

Tim Pietzcker


People also ask

Does else work with while?

In simple words, you can use the else block just after the for and while loop. Else block will be executed only if the loop isn't terminated by a break statement. To put it simply, we can say that if a loop is executed successfully without termination then the else block will be executed.

What is the difference between if and for loop?

A for loop executes a task for a defined number of elements, while an if statement tests a condition and then completes an action based on whether a result is true or false.

Why does Python use else after for and while loops?

In most of the programming languages (C/C++, Java, etc), the use of else statement has been restricted with the if conditional statements. But Python also allows us to use the else condition with for loops. The else block just after for/while is executed only when the loop is NOT terminated by a break statement.

What is the purpose of else in a loop?

Python - else in Loop The else block appears after the body of the loop. The statements in the else block will be executed after all iterations are completed. The program exits the loop only after the else block is executed.


2 Answers

The for else construct executes the else clause if no break statement was executed for the loop, as described here For example, this else clause is never evaluated

for i in range(1,10):
    if i % 5 == 0:
       print i
       break
else:
    print "nothing divisible by 5"
like image 156
Eli Courtwright Avatar answered Sep 20 '22 04:09

Eli Courtwright


Well, it depends how you see it. You can look at the elses like this (excuse the screaming, its the only way to make emphasis in code):

if condition:
   do_something()
IF THE PREVIOUS CONDITION WAS FALSE:
   do_something_else()

Now, there is an obvious similarity between if/else and try/except/else, if you see the else statement as an else to the except statement. Like this.

try:
   do_something()
IF THERE WAS AN EXCEPTION:
   pass:
IF THE PREVIOUS CONDITION WAS FALSE:
   do_something_else()
finally:
   cleanup()

Same goes for the else/for:

IF some_iterator IS NOT EMPTY:
   i = next(some_iterator)
   print(i)
IF THE PREVIOUS CONDITION WAS FALSE:
   print("Iterator is empty!")

So here we see that the else in some fundamental way do work exactly the same in all three cases.

But you can also see the else in this way:

try:
   do_something()
except someException:
   pass:
IF NO EXCEPTION:
   do_something_else()
finally:
   cleanup()

And then it's not the same anymore, but the else because a sort of "if nothing else". You can see for/else in the same way:

for i in some_iterator:
   print(i)
IF NO MORE ITERATING:
   print("Iterator is empty!")

But then again, considering the elif, then this way of seeing it works for if/else as well:

if condition:
   do_something()
elif otherconditaion:
   do_anotherthing()
IF NO CONDITION WAS TRUE:
   do_something_else()

Which way you want to look at the else is up to you, but in both ways of viewing, else do have similarities in all three cases.

like image 44
Lennart Regebro Avatar answered Sep 20 '22 04:09

Lennart Regebro