An addition to both for and while loops in Python that is not common to all languages is the availability of an else clause. The else block after a loop is executed in the case where no break occurs inside the loop.
The most common paradigm for using this clause occurs when evaluating a dataset for the occurences of a certain condition and breaking as soon as it is found. Rather than setting a flag when found and checking after to see the result, the else clause simplifies the code.
In the following example, if a multiple of 5 is found, the break exits the for loop without executing the else clause.
>>> for x in range(1,5): ... if x % 5 == 0: ... print '%d is a multiple of 5' % x ... break ... else: ... print 'No multiples of 5' ... No multiples of 5 >>> for x in range(11,20): ... if x % 5 == 0: ... print '%d is a multiple of 5' % x ... break ... else: ... print 'No multiples of 5' ... 15 is a multiple of 5
Without this feature, the code would look something like:
>>> found = False >>> for x in range(1,5): ... if x % 5 == 0: ... print '{0} is a multiple of 5'.format(x) ... found = True ... break ... >>> if not found: ... print 'No multiples of 5' ... No multiples of 5