In python most people are familiar with a combination of if / else or a while loop. Did you know you can combine a while with an else statement. the obvious main advantage here is to prevent using extra variables and nested statement which makes the code shorter and clearer to understand.
This short example demonstrates this functionality.
lst =  while lst: print "There is a list" break else: print "Empty List"
In the case above because the contents of the while loop are no executed because the list is empty it will print "Empty List" instead. This can also work with for loops like in the following example.
for x in lst: if x == "Something": DoSomething() break else: print "Not Found"
You should probably take notice of the break statements in the above code as the else statements runs on the last evaluation of the loop condition so when a loop terminates because its condition is false the else will always run. The break statement changes this so that the loop condition is true and the else will be skipped.
Did You find this page useful?
Thanks for the feeback. Please consider sharing with others.