Friday, 20 July 2012

For loop of Python


The for loop in python has the ability to iterate over the items of any sequence, such as a list or a string.
The syntax of the loop look is:

for iterating_var in sequence:
            statements(s)

if a sequence contains an expression list, it is evaluated first. Then, the first item in the sequence is assigned to the iterating variable iterating_var. Next, the statements block is executed. Each item in the list is assigned to iterating_var, and the statements(s) block is executed until the entire sequence is exhausted.

Note: in python, all the statements indented by the same number of character spaces after a programming construct are considered to be part of a single block of code. Python uses indentation as its method of grouping statements.

Example:

#!/usr/bin/python

for letter in ‘python’ :            #First Example
            print ‘Curre t Letter : ’, letter
fruits = [‘banana’, ‘apple’, ‘mango’]
for fruit in fruits:        #Second Example
            print  ‘Current fruit :’, fruit
print  “Good bye!”

This will produce following result:

Current Letter  :  P
Current Letter  :  y
Current Letter  :  t
Current Letter  :  h
Current Letter  :  o
Current Letter  :  n
Current fruit    : banana
Current fruit   : apple
Current fruit  :  mango
Good bye!

Iterating by sequence index:

An alternative way of iterating through each item is by index offset into the sequence itself:

Example:

#!/usr/bin/python

fruits = [‘banana’, ‘apple’, ‘mango’]
for index in range (len(fruits)):
              print  ‘Current fruit  :’,  fruits[index]
print “Good bye!”

This will produce following result:
Current fruit  : banana
Current fruit  : apple
Current fruit  : mango

Good bye!

No comments:

Post a Comment