For loop in Python

Hello friends how are you, today in this blog i will teach you what is for loop, syntax of for loop , how for loop works and many programs using for loop in a very simple way. 

Let's start
  • For loop is used for sequential traversal.
  • It can be used to traverse string or array.
  • Iterating over a sequence is called traversal.
  • 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
*/
  • We can also use else statement with for loop but it is not compulsory.
  • Else part will execute if the items in the sequence used in for loop exhausts.

Student=["Amisha","Rinkal","Mahima"]
for name in Student:
    print(name)
else:
    print("This is else block")
/*
### Output ###
Amisha
Rinkal
Mahima
This is else block
*/

  • For better understanding see the example.

Student=["Amisha","Rinkal","Mahima"]
for name in Student:
    if name=="Rinkal":
        break
    else:
        print(name)
else:
    print("This is else block")
/*
### Output ###
Amisha
because when if conditon will
become true (when name=Rinkal) the
break will terminate the loop
*/

Request:-If you found this post helpful then let me know by your comment and share it with your friend. 
If you want to ask a question or want to suggest then type your question or suggestion in comment box so that we could do something new for you all. 

If you have not subscribed my website then please subscribe my website. 

Try to learn something new and teach something new to other. Thanks.

Post a Comment

0 Comments