What is ‘for loop’?

For loop acts as an iterator in python which is an object that enables a programmer to traverse a container.

In short, for loop help us in doing the same type of task for a particular number of times.

Syntax of ‘for loop’

for element in object:
    #statement to perform action

Examples using ‘for loop’

# display pencil programmer 5 times using for loop
for element in range(0,5):
    print("pencil programmer")

Output

pencil programmer
pencil programmer
pencil programmer
pencil programmer
pencil programmer

The following example uses list.

#display numbers from 1 to 10 ten times
p=[1,2,3,4,5,6,7,8,9,10]
for integers in p:
    print p

Output

[1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
[1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
[1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
[1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
[1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
[1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
[1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
[1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
[1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
[1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
# check even or odd from given list
l=[1,2,3,4]
for integer in l:
    if integer%2==0:
        print(integer," :even number")
    else:
        print(integer," :odd number")

Output

1  :odd number
2  :even number
3  :odd number
4  :even number
#check odd number from 0 to 10,for even use (integer%2==0)
for integer in range(0,10):
    if integer%2!=0:
        print integer

Output

1
3
5
7
9
#find the sum of 10 number in range(0,10) [In range last element is excluded.]
sum=0
for integer in range(0,10):
    sum=sum+integer
print(sum)

Output

45
#print each string seperately
string='pencil programmer'
for element in string:
    print(element)

Output

p
e
n
c
i
l
 
p
r
o
g
r
a
m
m
e
r

The following example uses list as well as tuple.

display only 1st element from each bracket/tuple
l=[(1,2),(1,2),(1,2)]
for (p1,p2) in l:
    print(p1)

Output

1
1
1

Comment your doubts in the comment section.

Leave a Reply

eleven + 12 =