14.Looping(Iteration )Statement- while, for

We know that computers are often used to automate the repetitive tasks. One of the advantages of using computer to repeatedly perform an identical task is that it is done without making any mistake. Loops are used to repeatedly execute the same code in a program. Python provides two types of looping constructs:

1) while statement
2) for statement

while loop

The while loop in Python is used to iterate over a block of code as long as the test expression (condition) is true.

We generally use this loop when we don't know the number of times to iterate beforehand.

Syntax of while Loop in Python 
while test_expression: 
     Body of while

In the while loop, test expression is checked first.The body of the loop is entered only if the test_expression evaluates to True. After one iteration, the test expression is checked again. This process continues until the test_expression evaluates to False.

In Python, the body of the while loop is determined through indentation.The body starts with indentation and the first unindented line marks the end.

Python interprets any non-zero value as True. None and 0 are interpreted as False.
                                                                   
Example:
Sum of numbers from 1 to 10
i=1
sum=0
while i<=10:
     sum=sum+i
     i=i+1
print("Sum=",sum)
output
Sum=55
Note: 
while loop may not execute even once, if the condition evaluates to false initially, as the condition is tested before entering the loop.The body of the loop should change the value of one or more variables so that eventually the condition becomes false and the loop terminates. Otherwise the loop will repeat forever, which is called an infinite loop.
 
while loop with else

while loops can also have an optional else block.The else part is executed if the condition in the while loop evaluates to False.

The while loop can be terminated with a break statement. In such cases, the else part is ignored. Hence, a while loop's else part runs if no break occurs and the condition is false.

Here is an example to illustrate this.
Example:
i= 0
while i < 3: 
    print("Inside loop") 
    i = i + 1
else: 
    print("Inside else")
output
Inside loop
Inside loop
Inside loop
Inside else

for loop

The for loop in Python is used to iterate over a sequence (list, tuple, string) or other iterable objects. Iterating over a sequence is called traversal.

Syntax of for Loop:

for val in sequence: 
      body of for

Here, val is the variable that takes the value of the item inside the sequence on each iteration.

Loop continues until we reach the last item in the sequence. The body of for loop is separated from the rest of the code using indentation.

Example:
for c in "Python":
   print(c)
output:
P
y
t
h
o
n

The range() function

We can generate a sequence of numbers using range() function. range(10) will generate numbers from 0 to 9 (10 numbers(0-9) excluding 10).

We can also define the start, stop and step size as range(start, stop,step_size). step_size defaults to 1 if not provided.

However in Python 3, range(5) returns a object of range type. This object can be iterated over to yield a sequence of numbers. No matter how big the range is, the object always has the same size. This is due to the fact that range(5) only stores the start, stop, step values, and calculates each item when it is needed.

The range object is "lazy" in a sense because it doesn't generate every number that it "contains" when we create it. However, it is not an iterator since it supports in, len and __getitem__ operations.

This function does not store all the values in memory; it would be inefficient. So it remembers the start, stop, step size and generates the next number on the go.This is called lazy evaluation(deferred evaluation) Lazy Evaluation is an evaluation strategy which delays the evaluation of an expression until its value is needed and which also avoids repeated evaluations.

To force this function to output all the items, we can use the function list().

The following example will clarify this.
>>>print(range(10)) 
range(0, 10)
>>>print(list(range(10)))
[0,1,2,3,4,5,6,7,8,9]
We can use the range() function in for loops to iterate through a sequence of numbers.

Example of for loop with range() function.
This will print 1 to 10

for i in range(1,11):
    print(i,end=',')
output:
1,2,3,4,5,6,7,8,9,10

The following loop will count down
for i in range(10,0,-1):
    print(i,end=',')
output:
10,9,8,7,6,5,4,3,2,1
Note:Loops that count through a range of numbers are also called count controlled loops
for loop with else
A for loop can have an optional else block as well. The else part is executed if the items in the sequence used in for loop exhausts.

for i in range(5):
   print(i)
else:
   print("end of loop")

output
0
1
2
3
4
end of loop

Note:
The for loop can be used effectively to process list,tuple,dict,string, files etc..

Let‟s look at the equivalence of the two looping construct:
while

for
i= initial value
while ( i <limit):
     statement(s)
     i+=step
for i in range (initial value, limit, step):
      statement(s)

Comments

Popular posts from this blog

Python For Machine Learning - CST 283 - KTU Minor Notes- Dr Binu V P

46.Classes and Objects in Python- Accessors and mutators

KTU Python for machine learning Sample Question Paper and Answer Key Dec 2020