0

I was going through this. Coming from C environment, it hit me right in the face with utter surprise and disbelief. And, then I tried it for myself::

bCondition = True
while bCondition:
  print("Inside while\n")
  bCondition = False
else:
  print("Inside else\n")
print("done\n")

This code renders the below output,

#Output
Inside while
Inside else
done

Ideone link

Now, my question is, Why? why do we need this? Why both the blocks are executed? Isn't if and else were made for each other, then what use case will make this design a useful design to implement?

Again if we just change the code to incorporate a break, the behavior is more mysterious. Ideone Link.

bCondition = True
while bCondition:
  break
else:
  print("Inside else\n")
print("done\n")

This code renders the below output,

#Output
done

Why both of the blocks are skipped? Isn't break made to break out of the loop only, then why is it breaking out of the else block?

I went through the documentation too, couldn't clear my doubts though.

Abhineet
  • 5,320
  • 1
  • 25
  • 43
  • 2
    _A break statement executed in the first suite terminates the loop without executing the else clause’s suite._ - what is unclear in this sentence? I agree it's weird but nevertheless it's part of specification. You are not forced to use this form. – Łukasz Rogalski Feb 04 '16 at 11:09
  • 2
    take a look at this http://stackoverflow.com/questions/3295938/else-clause-on-python-while-statement – Luis González Feb 04 '16 at 11:10
  • don't use `else` in a `while`. – dsgdfg Feb 04 '16 at 11:58

1 Answers1

4

The use of the else clause after a loop in python is to check whether some object satisfied some given condition or not.

If you are implementing search loops, then the else clause is executed at the end of the loop if the loop is not terminated abruptly using constructs like break because it is assumed that if break is used the search condition was met.

Hence when you use break, the else clause is not evaluated. However when you come out of the loop naturally after the while condition evaluates to false, the else clause is evaluated because in this case it is assumed that no object matched your search criteria.

for x in data:
    if meets_condition(x):
        print "found %s" % x
        break
else:
    print "not found"
    # raise error or do additional processing 
bruno desthuilliers
  • 75,974
  • 6
  • 88
  • 118
raltgz
  • 69
  • 3