How to use for loop in python programming

Introduction

Loops in the program are used to iterate over the sequence of elements. In python, there are two primitive loops command i.e. for loop and while loop. However, in this blog, we will learn everything we need to know about for loop in python programming.

for loop in python

The for loop in python iterates over the items of any sequence be it a list or a string. Moreover, using for loop in the program will minimize the line of code.

Syntax:

for loop

Points to keep in mind while using for loop in python:

  1. It should always start with for keyword and should end with a colon(:).
  2. The statements inside the loop should be indented(four spacebars).

Example(Looping through String):

Strings are iterable objects since it contains a sequence of characters.

for i in "Bhutan":
	print(i)

Output:

B
h
u
t
a
n

Example(Looping through a list):

fruits = ['mango', 'apple', 'guava', 'orange']
for choice in fruits:
    if choice == 'mango':
        print('mango is already in the fruit list.')
    print(choice)

Output:

mango is already in the fruit list.
mango
apple
guava
orange

we will discuss more about lists in data structures.



range() function

To iterate over a sequence of numbers, the built-in function range() comes in handy. It generates arithmetic progressions. For example, if we want to print a whole number from 0 to 10, it can be done using a range() function in a for loop.

Example:

for i in range(11):
    print(i)

Output:

0
1
2
3
4
5
6
7
8
9
10

In the above example, number 11 is not printed as an output because the given endpoint is never a part of the generated sequence. That’s why it has printed till 10 which in total has 11 digits including 0.

In a range() function we can also define an optional start and the endpoint to the sequence. The start is always included while the endpoint is always excluded.

Example:

for i in range(2,10):
    print(i)

Output:

2
3
4
5
6
7
8
9

Moreover, the range() function also takes in another optional parameter i.e. step size. Passing step size in a range() function is important when you want to print the value uniformly with a certain interval.

Step size is always passed as a third parameter where the first parameter is the starting point and the second parameter is the ending point. And if the step_size is not provided it will take 1 as a default step_size.

For example, if we want to print all the even numbers between 0 and 20, we can pass a step value of 2.

for i in range(0,20, 2):
    print(i)

Output(all the even numbers from 0 till 20):

0
2
4
6
8
10
12
14
16
18

The important thing you need to know about the range() function is it does not store all the values in memory, it simply generates the next item on a go. Therefore, to force this function to output all the items, we can use the function list().

Example

print(range(10))
print(list(range(10)))
print(list(range(0,10))) # start value is 0 and end value is 10
print(list(range(0,10,2))) # start value is 0, end value is 10, and step value is 2

Output:

range(0, 10)
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
[0, 2, 4, 6, 8]


loop control statement

Loop control statements change execution from its normal sequence. When execution leaves a scope, all automatic objects that were created in that scope are destroyed. Python supports the following three control statements:

1. break statement

A break may only occur syntactically nested in a for or a while loop, but not nested in a function or class definition within that loop. It terminates the nearest enclosing loop, skipping the optional else clause if the loop has one. If a for loop is terminated by a break, the loop control target keeps its current value.

Example:

for i in range(10):
    if i == 3:
        break
    print(i)

Output:

0
1
2
2. continue statement

Continue may only occur syntactically nested in a for or a while loop, but not nested in a function or class definition within that loop. It continues with the next cycle of the nearest enclosing loop.

Example:

for i in range(5):
    if i == 3:
        continue
    print(i)

Output:

0
1
2
4
3. pass statement

Pass is a null operation — when it is executed, nothing happens. It is useful as a placeholder when a statement is required syntactically when no code needs to be executed.

Example:(nothing will be printed and there won’t be a syntax error)

for i in range(10):
    pass


else clause of for loop

Python supports having an else statement associated with loops, unlike other programming languages.  If the else statement is used with the for loop, the else statement will be executed when the loop has completed iterating the list or a string.

Syntax:

for expression:
   statement(s)
else:
   statement(s)

Example:

fruits = ['mango', 'apple', 'guava', 'orange']
for choice in fruits:
    if choice == 'mango':
        print('mango is already in the fruit list.')
else:
    print("Please have mango")

Output:

mango is already in the fruit list.
Please have mango

Note: If the break statement is executed inside the for loop then the “else” part is skipped. However, the “else” part is executed if there is a continue statement.

Example(for loop with a break statement):

for i in range(5):
    if i == 3:
        break
    print(i)
else:
    print("Not printed in presence of break statement")

Output:

0
1
2

Example(for loop with continue statement):

for i in range(5):
    if i == 3:
        continue
    print(i)
else:
    print("else statement executed in presence of continue statement")

Output:

0
1
2
4
else statement executed in presence of continue statement


nested for loop

Python programming language allows the use of one loop inside another loop and it is called a nested loop.

The syntax for nested for loop:

for iterator_var in sequence:
    for iterator_var in sequence:
        statement(s) 
    statement(s)

Example:

for i in range(1, 6): 
    for j in range(i): 
         print(i, end=' ') 
    print()

Output:

1
2 2
3 3 3
4 4 4 4
5 5 5 5 5