1

How does the code work even though the else statement is not aligned with the preceding if statement?

ret_code = -1
MAX_COUNT = 3
if ret_code < 0:
            for i in range(MAX_COUNT-1):
                print("sleep")
                ret_code = 4
                if ret_code >= 5:
                    break
            else:
                print(ret_code, '', 'Error')

Output is as follows:

Python 3.5.2 (default, Dec 2015, 13:05:11)
[GCC 4.8.2] on linux

sleep
sleep
4  Error

How does this work?

SRM
  • 29
  • 1
  • See also: [How can I make sense of the `else` clause of Python loops?](http://stackoverflow.com/questions/37642573/how-can-i-make-sense-of-the-else-clause-of-python-loops/37643358#37643358) – Moses Koledoye Mar 09 '17 at 18:39
  • @MosesKoledoye: now you can add other duplicates (since last week). I added yours. Super-nice gold badge feature. Use it! – Jean-François Fabre Mar 09 '17 at 18:58
  • @Jean-FrançoisFabre Just learning that from you. Sweet :) – Moses Koledoye Mar 09 '17 at 18:59
  • This is all very helpful, I was not aware of the the for-else clause in Python and did not know what to look for. Thanks! @Jean-FrançoisFabre – SRM Mar 10 '17 at 00:16

0 Answers0