Repeating a block of code using a sequence – for loop in Python

In a program, code is executed sequentially (line by line) but what if you want to do something repeatedly. For this functionality, loops are provided by different programming languages.

There are two types of loops in Python, while loop and for loop. In today’s post, we will be focusing on for loop.

A for loop executes a block of code repeatedly while iterating over the items of any sequence, such as a list or a string. The general syntax is as follows:

for var in sequence:
   line or block of code

The first value in the sequence is assigned to var on the first iteration and the line or block of code is executed. The value of var is updated to the next element in the sequence every time after the block is executed and the loop continues this way. When the sequence ends, the next line immediately following the loop is exected.

Following is a simple example of for loop iterating on a string:

for letter in “Hello”:
   print (“Current Letter is “ + letter)

This will produce the following output:

Current Letter is H
Current Letter is e
Current Letter is l
Current Letter is l
Current Letter is o

Following is a simple example of for loop iterating on a list:

friends = [“Bob”, “Joe”, “Sara”, “John”]
for friend in friends:
   print (friend + “is my friend”)

This will produce the following output:

Bob is my friend
Joe is my friend
Sara is my friend
John is my friend

Using else With A for Loop

If you want your program to execute a different statement or block of code once the sequence ends, you can use else keyword for it.

Let’s modify the above code to understand this.

friends = [“Bob”, “Joe”, “Sara”, “John”]
for friend in friends:
   print (friend + “is my friend”)
else:
    print(“No one else is my friend”)

When the above code is executed, it produces the following result:

Bob is my friend
Joe is my friend
Sara is my friend
John is my friend
No one else is my friend

Iterating Using Sequence Index

Instead of using the value, we can also use the index of the element to iterate over a sequence. In order to do this, we can use the range function of Python programming language. Following is a simple example:

friends = [“Bob”, “Joe”, “Sara”, “John”]
for itr in range(len(friends)):
   print (friends[itr] + “is my friend”)

The code will give the same output as above but the way it is executed is different. The len function gives the length of array and range gives a sequence of numbers from 0 to the length (excluded). We can easily index the array by using these numbers.

Imad

I am a Software Engineer with ample experience in making games, websites, mobile apps and augmented reality solutions.

Pin It on Pinterest