For loop in Python programming | Hands on coding

For loop
  1. For loop is used for sequential traversal.
  2. It can be used to traverse string or array.
  3. Iterating over a sequence is called traversal.
  4. For loop is used to iterate over a sequence(list,string tuple etc).

for variable in sequence:
    body of for_loop
  • Here for is keyword.
  • variable will take the value of the item inside the sequence on each iteration.
  • Here sequence may be string , array etc.

  • range() function is used to generate sequence of numbers.
  • Sequence of range function is range(start, stop, step_size).
  • Default step_size is 1.

/*This will generate numbers from 5 to 9*/
for x in range(5,10):
    print(x)
/*
### Output ###
5
6
7
8
9
*/

/*Here 5 is initial value 10 is final value
and step size is 2 so the output will be 5 7 9*/
for x in range(5,10,2):
    print(x)
/*
### Output ###
5
7
9
*/

str="Easy"
for x in str:
    print(x)
/*
### Output ###
E
a
s
y
*/

student=["Ravi","Rocky","Amisha"]
for x in student:
    print(x)
/*
### Output ###
Ravi
Rocky
Amisha
*/

/*taking user input of no*/
no=int(input("Enter any number:"))
print("Table of ",no," is given below")
for i in range(1,11):
    print(i*no)
/*
### Output ###
Enter any number:5
Table of  5  is given below
5
10
15
20
25
30
35
40
45
50
*/