Python Loops
Loops are used when same task needs to be executed multiple number of times.
Example, printing mathematical table of a number, printing a message 10 times, sending multiple requests to an end point, creating a menu based application which continues till the user wants etc.
Python provides following loop constructs:

1. while loop
This loop consists of a condition and a set of statements. Set of statements are executed repeatedly till the condition remains True or the condition evaluates to True.
There may be a single condition or multiple conditions separated by and/or operators.  Statements that are inside loop block are called Loop body.
All statements that are part of Loop body are indented, that is, they are at least one space more indented than loop condition and are at the same indentation level.
Syntax

while condition:
   # statement one
   # statement two
   # statement three
   # more statements

Example,

count = 0
# loop till count < 5
while count < 5:        
   # print count value
   print('Count is ' + str(count))  
   # increment count
   count = count + 1

Condition of loop is count < 5 which will remain True till count is less than 5. Loop body consists of 2 statements which are at same indentation level.
Output of the above loop will be

Count is 0
Count is 1
Count is 2
Count is 3
Count is 4

2. for loop

Python for loop can also be used to iterate till a condition remains True but its main use lies in its ability to iterate objects.

These objects may be data structures such as list, tupledictionary or in iterating over a sequence such as a string where it provides access to each item in the data structure and keeps on iterating till all the items are covered.
for loop syntax
Looking at both the above usages of for loop, its syntax can be generalized as below:

for <variable name> in <data structure or limit>:
     # statement one
     # statement two
     # other statements

Notice the in keyword and a colon(:) at the end. Also, all the statements of for loop are indented to denote that they belong to same block.
Using for loop
A for loop can be used in the following two scenarios.

Iterate using an index
Many times you want to iterate for a definite number of times using a counter or an index variable. Example, from 1 to 10. Using for loop this can be done as

for index in range(5):
   # prints 0 to 4
   print(index)

where index is a user defined variable and range() is an in-built method which returns a range of numbers starting from 0 to 1 less than the argument passed to it.
Thus, range(5) returns numbers from 0 to 4.

Iterate over a data structure
Suppose there is a list of items and you want to iterate it over that list using a for loop. Code will be

# create a list
fruits = ['papaya', 'orange', 'mango', 'banana'] 
for fruit in fruits:
    print(fruit)

Output of above code will be

papaya
orange
mango
banana

Loop with String
for loop can be used to iterate over a python string where element in each iteration will be a character. Example,

str = 'cat'
for char in str:
   print(char)

which prints

c
a
t

range() function
Python range() function generates a sequence of integers according to the arguments given to it.
range() function accepts following three arguments:
A. start
An integer which signifies the beginning value of the sequence to be generated. This is optional with a default value of 0.

B. end

An integer which signifies the end value of the sequence to be generated. This parameter is required.
Last value of the sequence generated by range() will be (end – 1).

C. step
An integer that defines the difference between the values generated. Thus, step size of 3 means two adjacent values will have a difference of 3.
step is optional with default value of 1.

for loop can be used to iterate over values generated by range() function using in operator. Thus, following is an example program to iterate 10 times using a for loop and range().

for num in range(10):
    print(num)

Else with for loop
Sometimes you want some code to be executed just after the loop ends or when there are no items left to be iterated.
For such cases, a for loop may be followed by an else block written using else statement. This block is optional. Example,

for x in 'cat':
   print(x)
else:
   print('End of characters')

which prints

c
a
t
End of characters

pass statement
If a for loop is written, it can not be empty, that is it should have at least one statement else there will be an error.
But if you want an empty for loop, may be for testing purpose, then write a pass statement inside the empty loop as shown below.

for x in range(3):
   pass

This loop will do nothing.
If you write pass in a loop that has other statements as well, then pass is completely ignored and the loop executes normally.
break statement
Python break statement is used to terminate a loop in between based on some condition.
Suppose you are searching for a name in a list of students using a loop. Now, it makes no sense to iterate further once the desired name is found. Example,

names = ['A', 'B', 'C' , 'D']
for name in names:
    if name == 'C':
        break
    print(name)

This prints

A
B

From the output, it is clear that the loop terminates in between.
Nested Loop
A loop inside another loop is called nested loop. A nested loop, also called inner loop is executed for each iteration of the outer loop just like any other statement written in outer loop.
Nested loop are mostly used for sorting structures where you need to compare each element with every other element or where there are two dimensional structures such as a matrix of numbers.
Example of a nested loop is

for x in range(3):
   for y in range(2):
      print('Outer variable = %d, Inner variable = %d' %(x,y))

which prints

Outer variable = 0, Inner variable = 0
Outer variable = 0, Inner variable = 1
Outer variable = 1, Inner variable = 0
Outer variable = 1, Inner variable = 1
Outer variable = 2, Inner variable = 0
Outer variable = 2, Inner variable = 1

Note that inner loop is completely executed for each iteration of outer loop, and

Total inner loop iterations = Outer loop iterations * Inner loop iterations per outer loop iteration

Hope the article was useful.

Leave a Reply