Python - for Loop Statements
Posted by JanWan
Last Updated: July 16, 2012

Python - for Loop Statements

A loop is a construct that causes a section of a program to be repeated a certain number of times. The repetition continues while the condition set for the loop remains true. When the condition becomes false, the loop ends and the program control is passed to the statement following the loop.

This tutorial will discuss the for loop construct available in Python.

The  for Loop:

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 'Current 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!

Here we took the assistance of the len() built-in function, which provides the total number of elements in the tuple as well as the range() built-in function to give us the actual sequence to iterate over.

 

Reference: http://www.tutorialspoint.com/python/python_for_loop.htm

 

J.W. PRODUCTION