top of page
hand-businesswoman-touching-hand-artificial-intelligence-meaning-technology-connection-go-

Loops in python



In computer programming, a loop is a sequence of instructions that is continually repeated until a certain condition is reached. We need loops when we want to execute a set of statements several times.

For example, I want to print ‘Hello’ 5 times. I need to write a code 5 times if I don’t use loops. As in below

print('Hello')
print('Hello')
print('Hello')
print('Hello')
print('Hello')

The output will be as follows

Hello 
Hello 
Hello 
Hello 
Hello

We can reduce the lines of code by using loops. In general, we have two types of loops. entry-controlled loops and exit-controlled loops. In entry controlled, the condition is checked first and the loop is executed if the condition is true. In the exit controlled, the loop is executed and then the condition is checked. This means that the exit-controlled loops are executed at least once. The control conditions should be well defined and specified properly, else the loop will execute an infinite number of times. An infinite loop is an endless loop.

The flow chart below shows the execution of the entry and exit controlled loops.


We have 3 kinds of loops in python

1) While loops

2) For loops

3) Nested loops


While Loop

The figure below shows the flow chart of a while loop. In a while loop, a condition is evaluated before processing a body of the loop. If a condition is true then and only then the body of a loop is executed.


The syntax for a while loop is as follows.



# Python program to illustrate
# while loop
count = 0
while (count < 5):
  count = count + 1
  print('Hello')

The above code will lead to the output as follows

Hello 
Hello 
Hello 
Hello 
Hello

Using else statement with while loops: As discussed above, while loop executes the block until a condition is satisfied. When the condition becomes false, the statement immediately after the loop is executed.

The else clause is only executed when our while condition becomes false. If we break out of the loop, or if an exception is raised, it won’t be executed. We can give all the valid comparisons in python as the condition in the while loop.

# Python program to illustrate
# while loop
count = 0
while (count < 5):
  count = count + 1
  print('Hello')
else:
  print('Inside the else loop')

The output is as follows

Hello 
Hello 
Hello 
Hello 
Hello 
Inside the else loop

For loops


A for loop is used to iterate over a sequence like lists, type, dictionaries, sets, or even strings. Loop statements will be executed for each item of the sequence.

The syntax for the for loop is as follows


#Python program to illustrate for loop
#Print Hello for 5 times
list = [1, 2, 3, 4, 5]
for num in list:
    print('Hello')

The output is as follows

Hello 
Hello 
Hello 
Hello 
Hello

The code snippet shows iteration through a list

#for statement to iterate through list
colors = ['red','blue','green','yellow']
print('Iterating through List')
for l in colors:
    print(l)

Output as follows

Iterating through List
red 
blue 
green 
yellow

The code below shows iteration through a tuple

#for statement to iterate through tuple
flowers = ('Rose','Lily','Jasmine','Daisy')
print('Iterating through Tuple')
for t in flowers:
    print(t)

The output is as follows

Iterating through Tuple
Rose 
Lily 
Jasmine 
Daisy

The code below shows iteration through a string

#for statement to iterate through String
name='MyName'
print('Iterating through String')
for s in name:
    print(s)

The output is as follows

Iterating through String
M
y
N
a
m
e

The code below shows iteration using a range

#for statement to iterate using a range
print('Iterating using range')
for i in range(0,3):
    print(i)

The output is as follows

Iterating using range
0
1
2

The code shows iterating over a dictionary

# Iterating over dictionary
print("Iteration over Dictionary ")  
d = dict()
d['xyz'] = 123
d['abc'] = 345
for i in d :
    print("%s  %d" %(i, d[i]))

The output is as follows

Iteration over Dictionary  
xyz  123 
abc  345

Using else statement with for loops: We can also combine else statement with for loop like in while loop. But as there is no condition in a for loop based on which the execution will terminate so the else block will be executed immediately after for block finishes execution.

iterator = (1, 2, 3, 4)
for item in iterator:
    print(item)
else:
    print("No more items in the iterator")

The output is as follows

1
2
3
4
No more items in the iterator

Nested Loops

There will be situations where we may need to execute a few statements when a condition is met. We can use any loop inside any loop. Like for loop inside a while loop or while loop inside a for loop. We can also use if condition inside a loop.

The code below will append all the even numbers in the given range to a list.

even_list = []
for item in range(1, 11):
    if item % 2 == 0:
        even_list.append(item)
print("Even Numbers: ", even_list)

The output of the code is as follows:

Even Numbers:  [2, 4, 6, 8, 10]

Loop control statement

In some cases, we may want to stop executing some commands when a condition is satisfied. We may want to come out of the loop when another condition is satisfied. Loop control statements are used when we want to change the execution flow of the statements.

There are 3 different kinds of loop control statements

1) continue

2) break

3) pass

Continue:

The flow chart for the continue statement is as follows

Let us take an example where we want to print the sequence of numbers only if it is not a multiple of 3

for item in range(1, 11):
    if item % 3 == 0:
        print('Not printing multiple of 3')
        continue
    print(item)

Here, the condition is checked every time and if the number is multiple of 3, then the print statement is not executed and the loop continues. We can see the output as follows

1 
2
Not printing multiple of 3 
4 
5
Not printing multiple of 3 
7 
8
Not printing multiple of 3
10

Break:

The flow chart for the break statement is as follows


Let us now print the letters in a word until either of the letters 'a','b', 'c' is encountered. Observe the code below


for val in "onetwothreearenumbers":
    if val == "a" or val=='b' or val=='c':
        break
    print(val)
print("The end")

The output will be as follows

o
n
e
t
w
o
t
h
r
e
e
The end

As soon as the letter 'a' is encountered, the break statement is executed and we exit from the loop.


Pass

A pass statement is a null statement. While the interpreter ignores the comments it will execute the pass statement. A loop cannot have an empty body. We may have a loop for which we want to add code in the future. In such cases, we use the pass statement. Pass statement can also be used in functions and classes.

for i in 'This is to execute pass':
  pass
print ('The value in i after the iteration through for loop is  '+i) 

This loop will just iterate through the string but do nothing. The output will be as follows

The value in i after the iteration through for loop is  s

Conclusion

Here we have discussed looping statements in python and how to use them .


595 views0 comments
bottom of page