Python for loop

in this section we will examine Python's for loop.
for <variable> in xrange(<an integer expression >):
	<statement-1 >
	<statement-n >  
The first line of code in Python for loop is sometimes called the loop header. an integer expression specifies that number of iterations of the loop. The colon : ends the loop header. Python for loop body consists the statements in the remaining lines of code, below the header. Python for loop body must be indented. The statements in for loop body are executed sequentially on each pass through the loop. Understand the Python for loop working let us discuss a example
Executing a statement a given number of times
If you want to print any statement multiple times say four times. This can easily be done by for loop.

Example 2:

for each in xrange(4):
   print "Hello all"
Print hello using Python for loop
Python for loop
In next program you will how to access the values of xrange() .

Example 3:

for count in xrange(4):
   print count
python for loop using xrange()
for loop
The out-put is print in top to bottom, however you can print values from left to right by using "," as shown in example 4.

Example 4:

for count in xrange(4):
   print count,
python for loop using xrange()
for loop printing count
In above example count start from 0 to 3 means one minus to integer expression.

Example 5:

product =1
for count in xrange(1,5):
   product = product*count
   print product,
Python for loop lower to upper bound of xrange()
for loop lower to upper bound
In above example the four numbers are printed. So you will have to give upper bound + 1 to print 5 numbers.
You can use a list instead of xrange().

Example 6:

for count in [1,2,3,4,5,8]:
   print count,
Python for loop using list
for loop using list

Using string in for loop

Example 7:

for each in 'mohitraj' :
   print each,
Python for loop using string
for loop using string
The letters of string printing one by one.