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)  

python-for-loop
python-for-loop

Example

  1. i=1  
  2. n=int(input("Enter the number up to which you want to print the natural numbers?"))  
  3. for i in range(0,10):  
  4.     print(i,end = ' ')  

Output:

0 1 2 3 4 5 6 7 8 9

Python for loop example : printing the table of the given number

  1. i=1;  
  2. num = int(input("Enter a number:"));  
  3. for i in range(1,11):  
  4.     print("%d X %d = %d"%(num,i,num*i));  

Output:

Enter a 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

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 of the nested for loop in python is given below.

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

Example 1

  1. n = int(input("Enter the number of rows you want to print?"))  
  2. i,j=0,0  
  3. for i in range(0,n):  
  4.     print()  
  5.     for j in range(0,i+1):  
  6.         print("*",end="")  

Output:

Enter the number of rows you want to print?5
*
**
***
****
*****

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

  1. for i in range(0,5):  
  2.     print(i)  
  3. else:print("for loop completely exhausted, since there is no break.");  

In the above example, for loop is executed completely since there is no break statement in the loop. The control comes out of the loop and hence the else block is executed.

Output:

0
1
2
3
4

for loop completely exhausted, since there is no break.

Example 2

  1. for i in range(0,5):  
  2.     print(i)  
  3.     break;  
  4. else:print("for loop is exhausted");  
  5. print("The loop is broken due to break statement...came out of loop")  

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

Output:

0

The loop is broken due to break statement...came out of loop

;