1.

Python offers two keywords – while and for – to constitute loops. Can you bring out the difference and similarity in their usage?

Answer»

SYNTAX of while loop:

while expr==True:     stmt1     stmt2     ..     .. stmtN

The block of statements with uniform indent is repeatedly executed till the expression in while statement remains true. Subsequent lines in the code will be executed after loop stops when the expression ceases to be true.

Syntax of for loop:

for x in interable:     stmt1     stmt2     .. stmtN

The looping block is executed for each item in the iterable object like list, or tuple or string. These objects have an in-built iterator that fetches ONE item at a time. As the items in iterable get exhausted, the loop stops and subsequent statements are executed.

The construction of while loop requires some mechanism by which the logical expression becomes FALSE at some point or the other. If not, it will constitute an infinite loop. The USUAL practice is to keep count of the number of repetitions.

Both types of loops allow use of the else block at the end. The else block will be executed when stipulated iterations are over.

for x in "hello":     print (x) else:     print ("loop over") print ("end")

Both types of loops can be nested. When a loop is placed inside the other, these loops are called nested loops.

#nested while loop x=0 while x<3:     x=x+1     y=0     while y<3:         y=y+1         print (x,y) #nested for loop for x in range(1,4):     for y in range(1,4):         print (x,y)

Both versions of nested loops print the following output:

1 1 1 2 1 3 2 1 2 2 2 3 3 1 3 2 3 3 1 1 1 2 1 3 2 1 2 2 2 3 3 1 3 2 3 3


Discussion

No Comment Found