In this tutorial you will master all about loops in python with examples; like for loop and while loop, their syntax and flowchart, and how loops can be nested. Also, we will learn the usage of keywords like a break, continue, and pass to control the flow of loops and how to use the range function in ‘for loop’ with examples.
Iteration is the process of repeating a set of codes for multiple instances or until they meet the condition. Two important factors associated with iteration are:
Iteration is also known as looping. This is because a sequence of instructions gets executed repeatedly one after the other until it meets the condition, hence forming a loop.
Iteration is broadly classified into types.
Consider the scenario where you have a set of codes and want to execute it for, say six times. One way to execute it is by writing the set of codes 6 times and executing it for 6 times. But it consumes lots of time and space.
So here comes a much easier way, ie., Definite Iteration. In definite iteration, the number of iterations is known prior to the execution of the loop body. Since the number of iterations is known we need to explicitly specify it at the start of the loop. We can make use of ‘For loop’ to illustrate the method of definite iteration.
The “for loop” often referred to as a “count controlled loop” is used to iterate over sequences like string, list, tuples, set, and dictionary. The number of iterations depends on the length of the sequence.
For <var> in <iterables>: <...........loop body…...>
varis the variable that takes the values within the iterables on each iteration.
Iteration stops when the variable reaches the last item of the sequence and the loop body is specified using indentation.
Note: Index variable initialization is not required in python for a loop.
Below examples show how looping works on a list and string.
#List is iterable L = ['Red','Green','Blue'] for i in L: print(i) #String is iterable Str ='RGB' for x in Str: print(x) #integer is not iterable int = 8999 for i in int: print(i)
Red Green Blue R G B TypeError: 'int' object is not iterable
In the above example, List
L and String
Str are the iterables, and
i is the variable. On each iteration, variable
i takes the consecutive items in
Str and prints the result.
Sequential data types like List and string executes and outputs the result. On the other hand, integer type objects which are non-sequential outputs a
TypeError, which means integer-type objects are not iterable.
Note: In python, all data types which are a kind of collection or sequence are iterables.
Yet another but a constructive way to iterate through a sequence is by indexing. Indexing in for loop is not simple as that what we already learn in string and list. Before jumping to indexing let’s cognize with
len() function and
len() is a built-in function in python used to determine the length of the given sequence. In other words, the len() function returns the total number of items in the sequence.
RGB’ is a string with length 3 and [‘Red’,’ Green’,’ Blue’] is a List with length 3.
range() function, typically, is used to generate a sequence of numbers.
Where, start denotes the start position of the sequence, defaults to
0 stop denotes the end position of the sequence, not included in seq. step denotes the incrementation, defaults by
print(list(range(6))) print(list(range(2,6))) print(list(range(2,6,2)))
[0, 1, 2, 3, 4, 5] [2, 3, 4, 5] [2, 4]
Range() function can be used in a for loop to iterate over items in a sequence using indexing. The below example will clarify the concept.
L = ['Red','Green','Blue','Black'] for i in range(1,len(L),2): print(L[i])
Indefinite iteration is used in situations where we don't know the number of executions beforehand. Here, the execution of codes takes place as long as the condition consummates. While loop comes under indefinite iteration.
While also known as a condition controlled loop is used to iterate a set of codes as long as it fulfills the condition. If it fails to meet the condition then loops terminate and control moves to the outside statements.
: <body of while>
count = 0 while(count<5): count=count+1 print(count)
1 2 3 4 5
In this example,
Note: Keep in mind to use indentation while using the loops in python.
A loop can be interrupted at any point in python using the keywords “break” or continue. The break statement is used to terminate the loop whereas the continue statement is used for continuing the loop by skipping some codes in the loop.
The break statement, as its name indicates, breaks the program flow at some point when it satisfies a particular condition. In other words, the break statement terminates the loop once it meets the given condition and shifts the control to the very next statement outside the loop.
Here is the syntax of the break statement in loops.
For <var> in <iterables>: <...........loop body…...> If <condition>: break
While <condition 1>: <body of while loop> If <condition 2>: break
L = ['Red','Green','Blue','Black','White'] for i in range(len(L)): if L[i]=='Blue': break print(L[i]) print('Program Ends Here')
Red Green Program Ends Here
count = 0 while(count<5): count=count+1 if count==3: break print(count)
The continue statements, as its name entails, continue the loop by skipping some set of codes that fulfills the condition provided. Continue statement never terminates the loop as like break statement.
Here is the syntax of the Continue statement in loops
For <var> in <iterables>: <...........loop body…...> If <condition>: continue
While <condition 1>: <body of while loop> If <condition 2>: continue
L = ['Red','Green','Blue','Black','White'] for i in range(len(L)): if L[i]=='Blue': continue print(L[i]) print('Program Ends Here')
Red Green Black White Program Ends Here
count = 0 while(count<5): count=count+1 if count==3: continue print(count)
1 2 4 5
One of the unique features that python allows is the use of optional else block at the end of the loops. The syntax of the else block is given below for both for loop and while loop.
For <var> in <iterables> <...........loop body…...> else: <Statement(s)>
While <condition > <body of while loop> else: <Statement(s)>
Str ='RGB' for i in Str: print(i) else: print('loop exits as string reaches its last character')
R G B loop exits as string reaches its last character
count = 0 while(count<5): count=count+1 print(count) else: print('Loop exits as count is no longer less than 5')
1 2 3 4 5 Loop exits as count is no longer less than 5
Python programming language also allows the principle of nesting in loops. A nested loop is a loop containing another loop. Nesting can be done to any level however it is convenient to nest to 2 or 3 levels deep because the higher the level is higher the complexity and prone to error.
For <var> in <iterables>: For <var> in <iterables>: <loop body> <loop body>
While <condition 1>: While <condition 2>: <body of while loop> <body of while loop>
Here in the above syntax, we saw a for loop inside another for loop and while loop inside another while. This nesting concept is illustrated below
L1 = ['Red','Green','Blue'] L2 = ['Car','Colour','Stone'] for i in L1: for j in L2: print(i,j) print('\n')
Red Car Red Colour Red Stone Green Car Green Colour Green Stone Blue Car Blue Colour
i=1 while(i<=3): j=0 while(j<3): j=j+1 print(i,'*',j,'=',i*j) i=i+1 print('\n')
1 * 1 = 1 1 * 2 = 2 1 * 3 = 3 2 * 1 = 2 2 * 2 = 4 2 * 3 = 6
Similarly, we can enclose a for loop inside a while loop and a while loop inside a for loop. But the fact that you need to bear in mind is about the use of indentation. Below examples shows how a for loop is nested inside a while loop.
i=1 while(i<=3): L2 = ['Car','Colour','Stone'] for j in L2: print(i,j) i=i+1
1 Car 1 Colour 1 Stone 2 Car 2 Colour 2 Stone 3 Car
The pass statement in python is a null statement used to implement stubs. The pass statement typically acts as a placeholder in a python program.
Python does not allow loops to be empty. To avoid getting errors in such situations we make use of the pass statement. Unlike comments, the pass statement is not ignored by the python interpreter instead Interpreter executes the pass statement. The result of the pass statement will be a no-operation as nothing happens when a pass statement is executed.
Str ='RGB' for i in Str: pass