For Loop in Python

In the previous article we explore the use of the range( ) function in Python, in this article we will explore another important kind of loop, that is the For Loop. A  for loop in the Python programming language is designed to iterate over the elements of data structures and some other objects. It is not a loop with a counter, as is the case for in many other languages. What does iteration of elements mean? For example, we have a list of a number of items. First, we take the first element from it, then the second, then the third, and so on until the end. It traverses list and tuples, strings, dictionary keys, and other iterable data types.

Working with For Loop in Python

In Python, a loop starts with a keyword for followed by an arbitrary variable name that will hold the values ​​of the next sequence object. The general syntax for..lop in python is as follows:

for x in seq:
    Statement 1
    Statement 2
    Statement 3

Let us look at an example of traversing list elements using For Loop:

l=[10, 20, 30,40]
for x in l:
    print(x)
Output:
10
20
30
40

Let us look at the use of For loop in traversing string:

s="gfg"
for x in s:
    print(x)
Output:
g
f
g

The range( ) function mentioned in the previous article is frequently used alongside the for loop statement.

for x in range (5):
    print(x)
Output:
0
1
2
3
4

Creatively the for loop can be used to exclude or only include certain numbers from a specified range.

for x in range(20):
    if x%6==0:
         print(x)
Output:
0
6
12
18
l = [ 10,20,30,40]
for i in range(len(l)):
    print(l[i])
Output:
10
20
30
40

Hence, we have explored the use of the For Loop in Python, and it’s structure. In the next article we will explore multiplication Table of a number.

Leave a Comment