Python Loops

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.

What is an iteration in python?

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:

  • Iterators refer to an object that holds the countable values in the iteration.
  • Iterables refer to an object that can be repeated or iterated over.

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.

  1. Definite Iteration - for loop
  2. Indefinite Iteration - While loop

What is a Definite Iteration in python?

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.

For loop in python

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.

Syntax of for Loop


For  <var>  in  <iterables>:
     <...........loop body…...>
 

Where

  • var is the variable that takes the values within the iterables on each iteration.
  • Iterables are the sequences like string, list, tuples, etc.

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.

Python For Flowchart

Example of for 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) 

Output:

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 L and 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.

The range() Function and Indexing

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 range() function.

  1. len() function

    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.

    Syntax:

    
    len(seq)
     
    

    RGB’ is a string with length 3 and [‘Red’,’ Green’,’ Blue’] is a List with length 3.

  2. Range() Function

    range() function, typically, is used to generate a sequence of numbers.

    Syntax:

    
    range( start,stop,step)
     
    

    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 1.

    Example: List Range function in 3 different ways

    print(list(range(6)))
    print(list(range(2,6)))
    print(list(range(2,6,2))) 
    

    Output:

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

    How to use the range() function in for loop?

    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.

    Example: range() function in for loop

    L = ['Red','Green','Blue','Black']
    for i in range(1,len(L),2):
        print(L[i]) 
    

    Output:

    Green
    Black
    

Indefinite Iteration

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 loop in python

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.

While loop Syntax


while :
     <body of while>
 

While loop Flowchart

Python While Flowchart

Example of while loop:


count = 0
while(count<5):
   count=count+1
   print(count)
 

Output:


1
2
3
4
5

In this example,

  • The index variable is initialized to zero
  • Next comes the condition where we check if the value of the count variable is less than 5. As long as the condition remains true, the body of while executes.
  • Afterward the control switches to the body of while loop body which includes two statements.
    • The increment statement increments the value of the count variable. What happens if we skip this step? Obviously, execution of the loop goes on and on and will never end. So this step is a must while using a while loop.
    • Next is the print statement which prints the value of the count variable.
  • The loops continue until their condition fails and exits the loop.

Note: Keep in mind to use indentation while using the loops in python.

The break and continue statements in loops

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

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.

The syntax of the break statement in for loop


For  <var>  in  <iterables>:
     <...........loop body…...>
     If <condition>:
        break
 

The syntax of the break statement in the while loop


While <condition 1>:
 <body of while loop>
   If <condition 2>:
        break
 

Flowchart of break statement in loops.

Python Break Flowchart

Example: Illustrates the break statement inside for loop


L = ['Red','Green','Blue','Black','White']
for i in range(len(L)):
 if L[i]=='Blue':
  break
 print(L[i])
print('Program Ends Here')
 

Output:


Red
Green
Program Ends Here

Example: Illustrates the break statement inside while loop


count = 0
while(count<5):
 count=count+1
 if count==3:
  break
 print(count)
 

Output:


1
2

The Continue Statement

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

The syntax of the Continue statement in for loop


For  <var>  in  <iterables>:
     <...........loop body…...>
     If <condition>:
        continue
 

The syntax of the Continue statement in the while loop


While <condition 1>:
 <body of while loop>
   If <condition 2>:
        continue
 

Flowchart of continue statement

Python Continue in Loop

Example: To illustrates the use of continue statement in for loop.


L = ['Red','Green','Blue','Black','White']
for i in range(len(L)): 
 if L[i]=='Blue':
  continue
 print(L[i]) 
print('Program Ends Here')
 

Output:


Red
Green
Black
White
Program Ends Here

Example: To illustrates the use of continue statements in a while loop.


count = 0
while(count<5):
 count=count+1
 if count==3:
  continue
 print(count)
 

Output:


1
2
4
5

The Else block in loops

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.

The syntax of The Else block in for loop


For  <var>  in  <iterables>
     <...........loop body…...>
    else:
       <Statement(s)>

 

The syntax of The Else block in while loop


While <condition >
 <body of while loop>
  else:
       <Statement(s)>
 

The placed inside an else clause will get executed only when the loop ends “by depletion”—means, the loop iterates until the controlling condition evaluates to false, and the else part is executed only after that. If the loop is terminated by a break statement, then the else clause fails to get executed.

Example: Else block in for loop


Str ='RGB'
for i in Str:
 print(i)
else:
 print('loop exits as string reaches its last character')
 

Output:


R
G
B
loop exits as string reaches its last character

Example: Else block in while loop

count = 0
while(count<5):
 count=count+1
 print(count)
else:
 print('Loop exits as count is no longer less than 5')
 

Output:


1
2
3
4
5
Loop exits as count is no longer less than 5

Python Nested Loops

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.

The syntax of The Nested loop in for loop


For  <var>  in  <iterables>:
    For  <var>  in  <iterables>:
        <loop body>
     <loop body>
 

The syntax of The Nested loop in while loop


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

Example: Nested For Loop


L1 = ['Red','Green','Blue']
L2 = ['Car','Colour','Stone']
for i in L1:
 for j in L2:
  print(i,j)
  print('\n') 
 

Output:


Red Car
Red Colour
Red Stone

Green Car
Green Colour
Green Stone

Blue Car
Blue Colour

Example: Nested While loop


i=1
while(i<=3):
 j=0
 while(j<3):
  j=j+1
  print(i,'*',j,'=',i*j)
 i=i+1
 print('\n')
 

Output:


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.

Example: for loop inside a while loop


i=1
while(i<=3):
 L2 = ['Car','Colour','Stone']
 for j in L2:
  print(i,j)
 i=i+1
 

Output:


1 Car
1 Colour
1 Stone

2 Car
2 Colour
2 Stone

3 Car

Python Pass Statement

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.

Example: Illustrates pass statement acting as a placeholder in loops


Str ='RGB'
for i in Str:
    pass