×


Python For Loops in Linux - Step by step guide ?

A for loop is used for iterating over a sequence (that is either a list, a tuple, a dictionary, a set, or a string). With the for loop we can execute a set of statements, once for each item in a list, tuple, set etc.

Here at Ibmi Media, as part of our Server Management Services, we regularly help our Customers to perform related Python queries.

In this context, we shall look into how to use the for loop in Python.


What is a for loop in Python ?

The for loop iterates through a string sequentially. The for loop doesn't need a variable reservation.


What is the Syntax of for Loop ?

The syntax of for Loop in python is given below:

for val in sequence:
    loop body

Here, val is the variable that takes the value of the item inside the sequence on each iteration.

Loop continues until we reach the last item in the sequence. The body of for loop is separated from the rest of the code using indentation.


Examples of using For Loops in Python

1. Consider the below for loop:

list = ["adelaide", "melbourne", "perth"]
for x in list:
print(x)

It's output will give:

adelaide
melbourne
perth


2. Loop with string

Here, we will try repeating the letters of the word "Australia":

for x in "tiger":
print(x)

The Output will be:

a
u
s
t
r
a
l
i
a


3. for loop with break statement

break statement allows stopping at the position we want.

Example 1: Exit the loop when x runs to "dog"

list = ["cat", "dog", "tiger"]
for x in list:
print(x)
if x == "dog":
break

The Output will be:

cat
dog


Example 2: Exit the loop when x has not reached the "dog"

list = ["cat", "dog", "tiger"]
for x in list:
if x == "dog":
break
print(x)

The output will be:

cat


4. for loop with continue statement

Continue statement allows to stop at the current position and continue at the next position.

For example, Don't print "dog":

list = ["cat", "dog", "tiger"]
for x in list:
if x == "dog":
continue
print(x)

The Output will be:

cat
tiger


5. for loop with pass statement

The for loop cannot be empty, but if for some reason we want to skip the loop with no content without error, then use the pass statement.

For Example:

The pass is added inside the function. It will get executed when the function is called as shown below:

def my_func():
    print('pass inside function')
    pass
my_func()

It's Output will give:

pass inside function


[Need support in fixing Python function issues ? We can help you. ]


Conclusion

This article covers how to use the for loop in Python. In fact, Python loops help to iterate over a list, tuple, string, dictionary, and a set.

There are two types of loop supported in Python "for" and "while". The block of code is executed multiple times inside the loop until the condition fails.