pythonpython-2.7for-loopfor-else

Need Help in Python if..for..else Loop


I'm new to programming and have found this if...for...else Loop, please help me understand it:

if(True):
    for i in range(0, 1):
        print i
    else:
        print 'x'

[written in Python 2.7] Which gives an Output:

0
1

This seems like it executes both the for loop and the else loop, but only else loop is not allowed. Why? What is the difference between this and the normal if...else loop?


Solution

  • This is a for - else loop. It executes the code in the for loop and if it completes normally it then executes the else clause. If however there is a break in the loop it is going to terminate it and not execute the else clause.

    You can read more about it here: http://book.pythontips.com/en/latest/for_-_else.html