Definite loop

It is a loop which is executed a set number of times. The best example that can be thought of a definite loop is a for loop. Let's take a look at the for loop:

Syntax
for <variable> in xrange(<an integer expression >):
<statement-1 >
<statement-n >

The first line of code in the for loop is sometimes called the loop header. An integer expression specifies the number of times the loop has to run. The colon : ends the loop header. Python's for loop block or body consists of the statements below the header that will be executed a set number of times. The for loop body must be indented. The statements inside the loop body are executed sequentially on each run. 

Let's try some example:

for a in xrange(4):
print "Hello all"

Here, in the preceding example, we are trying to print "Hello all" four times.

Here, a is any variable or iterating variable or counter variable whose initial value is 0 and will execute 4 times. Let's take another example:

for count in xrange(4): 
print count

Here the value of count will be printed one at a time and always on a new line.

In the preceding examples, the output is printed on a new line, but the output can be formatted to be printed in one line. For this, comma or , can be used as shown:

for count in xrange(4): 
print count,

The use of , will give you an output similar to this:

Let's consider some more examples:
product =1 
for count in xrange(1,5):
product = product*count
print product,

We are interested to print the product times count. For this, we create a variable product whose value we initialize with 1 and generate a list of numbers from 1 to 5, but not including 5. For one iteration of the for loop, the product is multiplied the number of times the count value.

Here, the count value is nothing but the numbers from our list. We will be getting an output as shown here:

Let's take another example of the for loop. Here, we are interested in printing each character in a given string:

for each in 'VIENNA PHILHARMONIC' :
print each,

For every single iteration of the for loop variable, each will store the value of every single character and will print them one by one in a single line, as shown here:

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.15.220.16