Understanding for loop in Python

In this tutorial, we will learn the functionality of for loop in Python. For loop is a very popular type of iterating statement among different programming languages such as C, C++, Java and Python etc. In Python, for loops are basically used when we need to iterate something over a given sequence or other types of iterable objects. This sequence can be list, tuple or string also. In for loop, we can also use the control variable to count the executions. That’s why for loop is also known as a counter-controlled loop.

Syntax of for loop in Python

Syntax :-  for value in sequence:
#body of this for loop

Let us consider some examples to get familiar with the concept:

n = ["code", "speedy", "codespeedy"]
for x in n:
  print(x)

Output :

code
speedy
codespeedy

Now let us take a single string:

for x in "codespeedy":
  print(x)

Output :

c
o
d
e
s
p
e
e
d
y

The range() function

By using range() function we can simply generate a sequence of numbers.

Syntax :- range (starting point, ending point, jumping steps)

Let us take some examples:

for n in range (5):
    print (n)

Output :

0
1
2
3
4

In this above example, the counter starts from 0 (by default) and ends with 4.

for n in range (1,5):
    print (n)

Output :

1
2
3
4

In this above example, the counter starts from 1 and ends with 4.

for n in range (1,5,2):
    print (n)

Output :

1
3

In this above example, the counter starts from 1 and ends with 4 with jumping over 2 steps each time.

The pass statement

In Python, we simply can’t create empty for loops. If we want to create empty for loop for any reason we have to pass the pass statement.

Example :-

for x in [1, 5, 2]:
  pass

Output :


Nested Loops in Python

In Python, we have the concept of nested loops (loop/loops under an outer loop) also.

Let us take an example:

for x in range(3): #outer loop
    for y in range(1, 4): #inner loop
        print(x, ",", y)

Output :

0 , 1
0 , 2
0 , 3
1 , 1
1 , 2
1 , 3
2 , 1
2 , 2
2 , 3

For loop with else block

In Python, we can also use an optional else block within a loop. Statements within the else will start it’s execution only after the successful executions of all the iterations of the loop.

Let us take an example:

for x in range(5):
    print(x)
else:
    print("Loop has ended")

Output :

0
1
2
3
4
Loop has ended

Leave a Reply

Your email address will not be published. Required fields are marked *