Python for Loop


In this section you will learn about the ‘for loop’ which is a counter control loop. In Python the ‘for loop’ is used to traverse through a sequence. A sequence may include a list, tuple or a string. This process is called traversing.

‘for loop’ executes one or more statements for a specified number of times. This loop is a counter controlled loop. It is the most flexible loop. That is why the most programmers use this loop in programs. The syntax of ‘for loop’ is given below:

 

Syntax of for loop

for val in sequence:

          body of for

In the above syntax val is that variable that will be assigned an item inside the sequence. The ‘for loop’ will be terminated when the loop will reach the last item of the sequence. Indentations are used to separate the body of the ‘for loop’ from other lines of the program.

 

Flowchart of for loop

The following is the flowchart of the ‘for loop’:

flowchart-of-for-loop

In the above flowchart the loop enters the sequence and is at item one of the sequence, then there is a condition that if the item is the last item of the sequence the loop should terminate and if the item is not the last item of the sequence then the loop should enter its body. This is how the ‘for loop’ works in Python.

 

EXAMPLE of for loop in Python

Consider the following example in which we have declared a list of integers and used a ‘for loop’ to traverse through the list and calculate the sum of all the integers appearing in the list:

CODE

>>> list = [2, 5, 6, 3, 4, 3, 9 ,8, 7, 5]

>>> sum = 0

>>> for values in list:

          sum = sum + values

>>> print(“The sum of all numbers in the list is: “, sum)

OUTPUT:

The sum of all numbers in the list is:  52

the-sum-of-all-numbers-in-the-list-is-52
The range () function

In Python the range function is used to create a list or a sequence of numbers for example the user wants to generate numbers from 0 to 4, this can be done by using the range function as range (5). This will create a sequence of numbers from 0 to 4 that is a total of 5 numbers will be generated.

In this way the range function is useful as it directly generate a sequence of numbers.

In the range () function the user can also define that from where the range should be started by defining an argument that is start. The start argument specifies the start of the range. The end of the range is specified by an argument known as stop.

There is another attribute step size which is used to define the difference between the numbers that is the increment between numbers.

Suppose the user wants to display number from 0 to 5 and he wants and increment of 2 between the numbers then he will use the step size of 2 then the number sequence will be 0, 2, and 4.

The syntax of the range () function is given below:

SYNTAX

range (start, stop, step size)

In the above syntax if the step size is not defined then the interpreter will assume the step size to be 1. The limitation of the range () function is that it does not have the ability to store all the numbers in the memory and hence it only creates a list of numbers at has defined starting and ending points.

In Python the list () function is used to output all the items in a sequence.

 

EXAMPLE of range () function

Consider the following example in which we have explained the functionality of the range () function:

CODE

print(range(5))

print(list(range(5)))

print(list(range(1,7)))

print(list(range(1,25,2)))

OUTPUT

range(0, 5)

[0, 1, 2, 3, 4]

[1, 2, 3, 4, 5, 6]

[1, 3, 5, 7, 9, 11, 13, 15, 17, 19, 21, 23]

In the above example, we have used the range () function in four different ways. In the first range () function, a range is defined that will have numbers from 0 to 5. It can be seen that all the numbers are not printed because we did not use the list () function.

In the second range () function the list () function is used and a range is defined inside the list () function. The list of integers contains numbers from 0 to 4 that is five numbers. It can be seen that when we used the list () function, we got the output.

In the third range () function the list () function is used and a range is defined inside the list () function. The range has the starting point 1 and the ending point 7. Note that 7 will not be printed.

In the fourth range () function the list () function is used and a range is defined inside the list () function. The range has the starting point 1 and the ending point 25. We have also defined the step size that is there should be an increment of 2 between each number hence the list is printed that was started from 1 and an increment of 2 and the ending point 25. Note that 25 will not be included.

In Python we can also use the range () function with the ‘for loop’ to traverse through the items of the sequence. The range () function can also be used with te len () function to traverse through the items of the sequence.

EXAMPLE

Consider the following example in which we used a for loop and a range () function inside the for loop and a len () function inside the range () function. The len () function is used for indexing through the items of the sequence.

CODE

>>> desert = [‘custard’, ‘trifle’, ‘Pie’]

>>> for j in range(len(desert)):

          print(“I will like to eat”, desert[j])

OUTPUT

I will like to eat custard

I will like to eat trifle

I will like to eat Pie

i-will-like-to-eat-pie

In the above example, we declared a list which is initialized with the names of different types of deserts and then used the len () function to iterate through the sequence. As there are three items in the list therefore, the ‘for loop’ will be executed three times. The loop has a counter variable that counts the items in the list and is used for printing.

 

for loop with else

In Python we can use the else part with the ‘for loop’, this is completely optional. The else part of the loop will be executed when the items of the sequence are exhausted in ‘for loop’. It means that when the point of termination of the loop becomes the else part will be executed.

In Python or any other programming language we can use the break statement also which will help to stop the loop. When the break statement is used the else part of the ‘for loop’ will be ignored that is the else part will not be executed.

 

EXAMPLE of for loop with else

Consider the following example, in which we have used, a ‘for loop’ with an else part and a break statement, the program is to find an integer from a list of integers:

CODE

>>> list = [3,7,4,6,8,9,2,1]

>>> n = 4

>>> for j in list:

          if n == j:

                   print (“The entered number is found in the list”)

                   break

          else:

                   print (“The entered number is not found in the list”)

OUTPUT

The entered number is not found in the list

The entered number is not found in the list

The entered number is found in the list

the-entered-number-is-found-in-the-listIn the above example, a list has been declared with some integers. Another variable is also declared that is assigned a value 4 and this is the value that we will find in the list. In the for loop j as the counter variable is declared that will traverse through the items of list.

Inside the ‘for loop’ there is an if statement that checks that if n means 4 becomes equal to j that has an initial value of 3 regarding to item of the list and then prints that number is found in the list and breaks the loop and if n is not equal to j then the else part will be executed and the loop will again start.

The integer n was found at location 3 or at item number 3 therefore, the loop was executed three times.