Topics

Looping in Python

Welcome to another tutorial, here you will learn about Loops in Python. In programming, looping is a functionality that is frequently used to achieve repetitive task programming. Although, it might vary from iterating each element of an array or strings, to modifying a whole database.

The thumb rule for using loops is:

Suppose, if you are writing a program over and over again, you need to use loops.

Rather than doing this:

>>> a = 1
>>> b = 2
>>> c = 3
>>> d = 4

 

Do it like this:

>>> a = []
>>> {run a loop in this line to store 1, 2, 3, 4 in list 

In the second example, looping was used, where we only have to write tedious tasks we have to achieve. With looping, we can achieve an iterative flow for execution.

 

There are two ways to achieve iterative flow in Python.

  • Using the for loop
  • Using the while loop

 

The for loop

Below is the syntax:

for [ELEMENT] in [ITERATIVE-LIST]:
	[statement to execute]
else:
	[statement to execute when loop is over]
	[else statement is completely optional]

 

A for loop is frequently used to iterate elements of lists. Check out the example below with the syntax above.

>>> myList = [8, 9, 2, 3, 4, 6]

 

Suppose, we want to iterate all the elements of the myList list using the for a loop.

for i in myList:
	print (i)

From the above example, the variable i was used to represent all the elements stored in the list, one after the other. Now, our loop will run as many times as there are elements in the lists. E.g. the list myList has 6 elements, so the loop in the above example will run 6 times.

Also, in course of the first iteration, the value of i will be 8, and the next will be 9, and so on till 6, the last iteration. With the continuous action, anyone can easily use these individual list element values inside the loop, just like the above example, we have printed them.

Aside, from this, there are other ways of iterating. Recall, our old traditional way of accessing an element of the list by index i.e. myList[i]. But, in this case, we are using another function range() ( alternatively xrange() can be used). Check out the example below:

>>> range(5)

Output:

[0, 1, 2, 3, 4]

 

Or

>>> range(5, 10)

Output:

[5, 6, 7, 8, 9]

 

Or

>>> range(2, 12, 2)

Output:

[2, 4, 6, 8, 10]

 

Furthermore, we can make use range() function along with the for loop to iterate the index number from 0 to len(myList). Check out the example below:

for i in range(0, len(myList)):
	print (myList[i])

From the example, it is clear that we iterated over a temporary list that contains the index numbers of the original list. Thus, this temporary list is generated using the range() function.

 

The else block in for loop

The else block with the for loop, is executed, immediately after all the elements of the list are iterated, or when there are no elements left to iterate in the list. It is quite proper to say that the else statement is executed at the end of the loop. But, it is optional to use it and if used, it is not frequent.

Check out a more complex example below:

>>> bigList = [[1, 3, 6], [8, 2,], [0, 4, 7, 10], [1, 5, 2], [6]]

Now, how do we access each element of the list? we can access each element by using the loop within another loop. This is because, there are lists within a list, thereby, the outer loop will help in accessing each list of the bigList. Also, inside the list, for each element, we will be using another loop.

for i in bigList:
	for j in i:
		print ("Element of list within a list - ", j)

Output:

Element of list within a list - 1 
Element of list within a list - 3 
Element of list within a list - 6 
Element of list within a list - 8 
Element of list within a list - 2 
Element of list within a list - 0 
Element of list within a list - 4 
Element of list within a list - 7 
Element of list within a list - 10 
Element of list within a list - 1 
Element of list within a list - 5 
Element of list within a list - 2 
Element of list within a list - 6

 

The while loop

Below is the syntax for the while loop. 

while [condition]:
	[statement to execute]
else:
	[statement to execute if condition is false]
	[else statement is completely optional]

Also, in the while loop, there is an else block, however, it is optional, and used rarely.

In the first statement, a while loop sets a condition, a statement, and the compiler following the flow of execution first checks the condition provided in the condition block, if the condition holds True, then the statement is executed.

 

After the statement is executed, the compiler checks the condition once more, and if it is True once more, then the statement is again executed, otherwise, the else block is executed (i.e. if provided) or simply the flow control breaks out of the while loop; that if the statement was not mentioned.

Check out the example below:

while True:
	print ("I am printing because the condition is True")

 

In the example, we set our condition to be True, so the compiler will execute the statement the first time. And for the next iteration, the condition will still be True again, and thus the statement will be executed once more. This iteration process will keep on repeating itself and will not end. This kind of loop is called an infinite loop and should be avoided in programs.

This is another example:

i = 0
while i < 5:
	i=i+1
	print ("i =", i)

 

In the example above, the first iteration condition i.e. i<5 is checked, because 0<5, thus the statement is executed. And then, during execution, the value of i is incremented by.

In addition, the for loop is commonly used for iterating elements of a list, and the while loop is capable of serving several purposes, and it can as well iterate a list. also, the logic is quite similar when accessing an element using indices. Check out the example below:

myList = [8, 9, 2, 3, 4, 6]
i = 0
while i < len(myList):
    print (myList[i])
    i = i+1;

 

Also, the below example is for lists within a list.

bigList = [[1, 3, 6], [8, 2,], [0, 4, 7, 10], [1, 5, 2], [6]]
i = 0
j = 0
while i<len(bigList):
	while j<len(bigList[i]):
		print (“Element of list within a list -”,bigList[i][j])
		j=j+1;
	i=i+1

 

The continue keyword

This keyword is typically used within loops for altering the loop execution. When using the continue keyword inside the loop will skip the current statement execution, and it will check the condition again. Check out the example below:

>>> name = "TutorialWithExample Python"

 

The example below demonstrates the use of the continue keyword.

for i in name:
	continue
	print (i)

 

From the example above, the code will print nothing. Let’s know why it is so. Now, for the first iteration, the first element of the list name will be picked. (i.e. “s”), the next statement inside the for loop continues, therefore, once this keyword is found, the execution of the rest of the for loop statements is then skipped and the flow gets back to the for loop starting to get the next element and then check the condition. In addition, similar steps are followed by the next element of our string (“t”), and the continue interrupts the flow, and this will repeat all the time the execution flow reaches the continue keyword.

Let’s look at something else. Suppose you want to write a program with a loop that will print only the lowercase letters of the string stored in the name variable, you can use the continue keyword to skip those letters which are not lowercase. This is shown below:

for i in name:
	if not i.islower():
		continue
	print (i)

 

From the example above, the if condition checks if the element i is in lowercase, by using islower() function. But, if the element is not in lowercase then the rest of the statements are simply skipped and the print statement is never executed, but, if the element is in lowercase then the if statement returns False, and the continue statement will not be executed.

From all that we have seen, you will agree with me that the continue keyword works exactly as the while loop.

 

The break keyword

This keyword is used inside the loop to break out of the loop. Take for instance, while iterating over the characters of the string stored in the variable name, and you want to break out of it as soon as the character "T" is encountered. Check out the example below:

for i in name:
	if i == "T":
		break;
	print (i)