Friday, 20 July 2012

The else Statement Used with Loops


Python supports to have an else statement associated with a loop statements.

·         If the else statement is used with a for loop, the else statement is executed when the loop has exhausted iterating the list.
·         If the else statement is used with a while loop, the else statement is executed when the condition becomes false.


Example:

The following example illustrates the combination of an else statement with a for statement that searches for prime numbers from 10 through 20.

#!/usr/bin/python

For num in range (10, 20):      #to iterate between  10  to  20
     For i in range  (2,  num)  : #to iterate on the factors of the number
            If  num% I == 0:           #to determine the first facto
               J = num/I                  #to calculate the second factor
              Print  ‘%d equals  %d * %d ‘  % (num, i, j)
              break             #to move to the next number, the #first FOR
else:                             #else part of the loop
print  num,  ‘is a prime number’

This  will produce following result:

10 equals 2*5
11 is a prime number
12 equals 2*6
13 is a prime number
14 equals 2*7
15 equals 3*5
16 equals 2*8
17 is a prime number
18 equals 2*9
19 is a prime number.

No comments:

Post a Comment