for Loop


☞ It is used to iterate over a sequence (such as a list, tuple, string, or range) or any other iterable object.

☞ It executes a block of code repeatedly for each item in the sequence.

Syntax :
 
for <control_variable> in <sequence/item/range>:
    # statements of for
else:           #optional
    #statements of else
NOTE : Here, we will discuss the for loop only with the range() function. for loop with sequence/items will be covered in related chapters.

Example 1 :
 
#To demonstrate range(<stop>) function
for i in range(5):
    print(i)
Output :
 
0
1
2
3
4
Example 2 :
 
#To demonstrate range(<start>, <stop>) function
for i in range(1, 5):
    print(i)
Output :
 
1
2
3
4
Example 3 :
 
#To demonstrate range(<start>, <stop>, <step>) function
for i in range(1, 5, 2):
    print(i)
Output :
 
1
3
Example 4 :
 
#To print numbers in reverse order
for i in range(5, 0, -1):
    print(i)
Output :
 
5
4
3
2
1
Example 5 :
 
#To print numbers in reverse order skipping 3 steps
for i in range(10, 0, -3):
    print(i)
Output :
 
10
7
4
1