Introduction to different types of Python Loops

If you are interested to learn about the Python statements

Python for loops are used to loop through an iterable object (like a list, tuple, set, etc.) and perform the same action for each entry. For example, a for loop would allow us to iterate through a list, performing the same action on each item in the list. The flow of the programs written in any programming language is sequential by default. Sometimes we may need to alter the flow of the program. The execution of a specific code may need to be repeated several numbers of times. For this purpose, The programming languages provide various types of loops which are capable of repeating some specific code several numbers of times. Consider the following diagram to understand the working of a loop statement.

Python Loops

Why we use loops in python?

The looping simplifies the complex problems into the easy ones. It enables us to alter the flow of the program so that instead of writing the same code again and again, we can repeat the same code for a finite number of times. For example, if we need to print the first 10 natural numbers then, instead of using the print statement 10 times, we can print inside a loop which runs up to 10 iterations.

Advantages of loops

There are the following advantages of loops in Python.

  1. It provides code re-usability.
  2. Using loops, we do not need to write the same code again and again.
  3. Using loops, we can traverse over the elements of data structures (array or linked lists).

There are the following loop statements in Python.

Loop StatementDescription
for loopThe for loop is used in the case where we need to execute some part of the code until the given condition is satisfied. The for loop is also called as a per-tested loop. It is better to use for loop if the number of iteration is known in advance.
while loopThe while loop is to be used in the scenario where we don’t know the number of iterations in advance. The block of statements is executed in the while loop until the condition specified in the while loop is satisfied. It is also called a pre-tested loop.
do-while loopThe do-while loop continues until a given condition satisfies. It is also called post tested loop. It is used when it is necessary to execute the loop at least once (mostly menu driven programs).

Python for loop

The for loop in Python is used to iterate the statements or a part of the program several times. It is frequently used to traverse the data structures like list, tuple, or dictionary. The syntax of for loop in python is given below.

  1. for iterating_var in sequence:    
  2.     statement(s)    

The for loop flowchart

Python for loop

For loop Using Sequence

Example-1: Iterating string using for loop

str = "Python"  <strong>for</strong> i <strong>in</strong> str:     <strong>print</strong>(i)  

Output:

P
y
t
h
o
n

Example- 2: Program to print the table of the given number

list = [1,2,3,4,5,6,7,8,9,10]  
n = 5  <strong>for</strong> i <strong>in</strong> list: 
  c = n*i     <strong>print</strong>(c)  

Output:

5
10
15
20
25
30
35
40
45
50s

Example-4: Program to print the sum of the given list.

list = [10,30,23,43,65,12]  
 sum = 0   <strong>for</strong> i <strong>in</strong> list:  
sum = sum+i   <strong>print</strong>("The sum is:",sum)  

Output:

The sum is: 183

For loop Using range() function

The range() function

The range() function is used to generate the sequence of the numbers. If we pass the range(10), it will generate the numbers from 0 to 9. The syntax of the range() function is given below.

Syntax:

  1. range(start,stop,step size)  
  • The start represents the beginning of the iteration.
  • The stop represents that the loop will iterate till stop-1. The range(1,5) will generate numbers 1 to 4 iterations. It is optional.
  • The step size is used to skip the specific numbers from the iteration. It is optional to use. By default, the step size is 1. It is optional.

Consider the following examples:

Example-1: Program to print numbers in sequence.

<strong>for</strong> i <strong>in</strong> range(10):    
<strong>print</strong>(i,end = ' ')  

Output:

0 1 2 3 4 5 6 7 8 9 

Example – 2: Program to print table of given number

n = int(input("Enter the number "))   <strong>for</strong> i <strong>in</strong> range(1,11):     c = n*i     <strong>print</strong>(n,"*",i,"=",c)  

Output:

Enter the number 10
10 * 1 = 10
10 * 2 = 20
10 * 3 = 30
10 * 4 = 40
10 * 5 = 50
10 * 6 = 60
10 * 7 = 70
10 * 8 = 80
10 * 9 = 90
10 * 10 = 100

Example-3: Program to print even number using step size in range()

n = int(input("Enter the number "))   <strong>for</strong> i <strong>in</strong> range(2,n,2): 
   <strong>print</strong>(i)  

Output:

Enter the number 20
2
4
6
8
10
12
14
16
18

We can also use the range() function with sequence of numbers. The len() function is combined with range() function which iterate through a sequence using indexing. Consider the following example.

list = ['Peter','Joseph','Ricky','Devansh']   <strong>for</strong> i <strong>in</strong> range(len(list)):  
   <strong>print</strong>("Hello",list[i])  

Output:

Hello Peter
Hello Joseph
Hello Ricky
Hello Devansh

Nested for loop in python

Python allows us to nest any number of for loops inside a for loop. The inner loop is executed n number of times for every iteration of the outer loop. The syntax is given below.

Syntax

  1. for iterating_var1 in sequence:  #outer loop  
  2.     for iterating_var2 in sequence:  #inner loop  
  3.         #block of statements     
  4. #Other statements    

Example- 1: Nested for loop

# User input for number of rows  rows = int(input("Enter the rows:")) 
  # Outer loop will print number of rows   <strong>for</strong> i <strong>in</strong> range(0,rows+1): 
 # Inner loop will print number of Astrisk   <strong>for</strong> j <strong>in</strong> range(i):  
  <strong>print</strong>("*",end = '')       <strong>print</strong>()  

Output:

Enter the rows:5
*
**
***
****
*****

Example-2: Program to number pyramid.

rows = int(input("Enter the rows"))  <strong>for</strong> i <strong>in</strong> range(0,rows+1):  
<strong>for</strong> j <strong>in</strong> range(i):   
 <strong>print</strong>(i,end = '')      <strong>print</strong>()  

Output:

1
22
333
4444
55555

Using else statement with for loop

Unlike other languages like C, C++, or Java, Python allows us to use the else statement with the for loop which can be executed only when all the iterations are exhausted. Here, we must notice that if the loop contains any of the break statement then the else statement will not be executed.

Example 1

<strong>for</strong> i <strong>in</strong> range(0,5):   
 <strong>print</strong>(i)    <strong>else</strong>:  
 <strong>print</strong>("for loop completely exhausted, since there is no break.")  

Output:

0
1
2
3
4
for loop completely exhausted, since there is no break.

The for loop completely exhausted, since there is no break.

Example 2

<strong>for</strong> i <strong>in</strong> range(0,5):       
 <strong>print</strong>(i)     <strong>break</strong>;  
  <strong>else</strong>:<strong>print</strong>("for loop is exhausted");   
 <strong>print</strong>("The loop is broken due to break statement...came out of the loop")    

In the above example, the loop is broken due to the break statement; therefore, the else statement will not be executed. The statement present immediate next to else block will be executed.

Output:

0

Python While loop

The Python while loop allows a part of the code to be executed until the given condition returns false. It is also known as a pre-tested loop. It can be viewed as a repeating if statement. When we don’t know the number of iterations then the while loop is most effective to use.

The syntax is given below.

  1. while expression:    
  2.     statements    

Here, the statements can be a single statement or a group of statements. The expression should be any valid Python expression resulting in true or false. The true is any non-zero value and false is 0.

While loop Flowchart

Python While loop

Loop Control Statements

We can change the normal sequence of while loop’s execution using the loop control statement. When the while loop’s execution is completed, all automatic objects defined in that scope are demolished. Python offers the following control statement to use within the while loop.

1. Continue Statement – When the continue statement is encountered, the control transfer to the beginning of the loop. Let’s understand the following example.

Example:

# prints all letters except 'a' and 't'   i = 0  str1 = 'javatpoint'   <strong>while</strong> i &lt;
 len(str1):     <strong>if</strong> str1[i] == 'a' or str1[i] == 't':  
       i += 1         <strong>continue</strong>     print('Current Letter :', a[i])       i += 1  

Output:

Current Letter : j
Current Letter : v
Current Letter : p
Current Letter : o
Current Letter : i
Current Letter : n

2. Break Statement – When the break statement is encountered, it brings control out of the loop.

Example:

# The control transfer is transfered  # when <strong>break</strong> statement soon it sees t  i = 0  str1 = 'javatpoint'   <strong>while</strong> i &lt; len(str1):  
<strong>if</strong> str1[i] == 't':   
 i += 1         <strong>break</strong>     print('Current Letter :'
, str1[i])      i += 1  

Output:

Current Letter : j
Current Letter : a
Current Letter : v
Current Letter : a

3. Pass Statement – The pass statement is used to declare the empty loop. It is also used to define empty class, function, and control statement. Let’s understand the following example.

Example –

# An empty loop   str1 = 'javatpoint'  i = 0    <strong>while</strong> i &lt; 
len(str1):       i += 1      pass   print('Value of i :', i)  

Output:

Value of i : 10

Example-1: Program to print 1 to 10 using while loop

i=1  #The <strong>while</strong> loop will iterate until condition becomes <strong>false</strong>.  While(i&lt;=10):     print(i)       i=i+1   

Output:

1
2
3
4
5
6
7
8
9
10

Example -2: Program to print table of given numbers.

i=1    number=0    b=9    number = <strong>int</strong>(input("Enter the number:"))    <strong>while</strong> i&lt;=10:      
 print("%d X %d = %d \n"%(number,i,number*i))        i = i+1    

Output:

Enter the number:10
10 X 1 = 10 

10 X 2 = 20 

10 X 3 = 30 

10 X 4 = 40 

10 X 5 = 50 

10 X 6 = 60 

10 X 7 = 70 

10 X 8 = 80 

10 X 9 = 90 

10 X 10 = 100 

Loop Control Statements in Python

Sometimes, you may want to break out of normal execution in a loop.

1. break statement

When you put a break statement in the body of a loop, the loop stops executing, and control shifts to the first statement outside it. You can put it in a for or while loop.

>>> <strong>for</strong> i <strong>in</strong> 'break': print(i) <strong>if</strong> i=='a': break;

Output

b
r
e

2. continue statement

When the program control reaches the continue statement, it skips the statements after ‘continue’. It then shifts to the next item in the sequence and executes the block of code for it. You can use it with both for and while loops.

>>> i=0>>> <strong>while</strong>(i&lt;8): i+=1 <strong>if</strong>(i==6): continue print(i)

Output1
2
3
4
5
7
8

If here, the iteration i+=1 succeeds the if condition, it prints to 5 and gets stuck in an infinite loop. You can break out of an infinite loop by pressing Ctrl+C.

>>> i=0>>> <strong>while</strong>(i&lt;8): <strong>if</strong>(i==6): continue print(i) i+=1

Output

01

2

3

4

5

3. pass statement

In Python, we use the pass statement to implement stubs. When we need a particular loop, class, or function in our program, but don’t know what goes in it, we place the pass statement in it. It is a null statement. The interpreter does not ignore it, but it performs a no-operation (NOP)

>>> <strong>for</strong> i <strong>in</strong> 'selfhelp': pass>>> print(i)

Outputp

To run this code, save it in a .py file, and press F5. It causes a syntax error in the shell.

Introduction to different types of Python Loops
Show Buttons
Hide Buttons