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"
    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":
    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?

Yes No

Last Modified: 19 February 2017

Releated Posts

2013-04-09 - Python - How to find out if a key exists in a dictionary
2012-08-14 - Python - while else statement
2012-06-30 - CPP - Creating A basic python wrapper
2012-02-22 - Python - 2d Arrays don't work.