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?
This is a
for - elseloop. It executes the code in theforloop and if it completes normally it then executes theelseclause. If however there is abreakin the loop it is going to terminate it and not execute theelseclause.You can read more about it here: http://book.pythontips.com/en/latest/for_-_else.html