By: Archana Shukla and Rajesh Shukla
Flow of execution
Iteration or looping construct
Looping constructs provide the capability of executing a set of statements in a program repetitively based on a condition. Python provides 2 types of looping constructs namely ‘for loop’ and ‘while loop’.
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
n=[1,2,3,4,5] for i in n: print(i)
Output:
1
2
3
4
5
range() function
We can generate a sequence of numbers using range() function. for example range(10) will generate numbers from 0 to 9 (10 numbers). We can also define the start, stop and step size as
Syntax:
range(start,stop,step_size)
step_size defaults to 1 if not provided.
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.
To force this function to output all the items, we can use the function list().
Note:
* In an above examples we have displayed only the range of numbers not the numbers.
* In order to print the numbers in the given range we can use list sequence.
Example: print number from 0 to 9
print(list(range(10)))
output
[0,1,2,3,4,5,6,7,8,9]
Example
print(list(range(1,21)))
Output:
[1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20]
Example
print(list(range(20,0,-1)))
Output:
[20, 19, 18, 17, 16, 15, 14, 13, 12, 11, 10, 9, 8, 7, 6, 5, 4, 3, 2, 1]
Example
n=list(range(1,21))
for i in n:
print(i)
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 beforehand, the number of times to iterate.
Syntax:
while test_expression:
Body of while
In 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.
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: To print nos from 1 to 10
i=1 while(i<=10): print(i) i=i+1
Example: To print all even nos upto 20
i=2 while(i<=20): print(i) i=i+2