Python Loops

by | Aug 7, 2021 | Python

Home » Python » Python Loops

Introduction

In programming, we often come across scenarios where we need to execute the block of code or statement several times. Here loops come into the picture. With the help of the looping technique, we can iterate the statements as many times as required.

Loops are an essential tool in programming to be able to iterate over a collection of data or otherwise. Python offers several looping techniques that are frequently used to loop over data. The fundamental three ways of loops in Python are While Loops, for in loops, and switch statements. While the basic functionality of the loops is similar, the syntaxes vary for each type.

 

Python Loops

Fig 1: Flow Diagram

Type of loops

In python we have three different types of loops:

Types Description
While loop The while loop checks for the condition in the beginning. If the condition computed is True, the loop body is executed.

Syntax : while <expression>:

statements

 

For loop The for loop iterates over the given sequence which stisfies the condition.

Syntax: for <value> in <sequence>:

Statement

 

Nested loop Using one loop statement inside another loop.

Syntax: for <value> in <sequence>:

If <condition>:

statement

Else:

statement

 

Examples

1. While loop

 

counter = 0

while (counter < 3):

counter = counter + 1

print(“Line”, counter)

Output:

While loop Output

2. For loop

 

for val in range(0, 5):

print(val)

Output:

For loop Output

3. Nested loop

n = 10

for val in range(0, n):

if val % 2 == 0:

print(val,'is even number')

else:

print(val,'is odd number')

 

Output:

Nested loop

While Loops

While loops are loops not bounded by the number of iterations. The concept of while loops is that these loops will execute until an exit condition is not fulfilled. When the exit condition is satisfied, the loop will terminate, and the next line of code will be executed.

Syntax:

while expression:
statement(s)

In Python, a block of code is represented by the indentation that appears before each line. If certain lines have the same indentation before them, then the lines belong to the same block. While using loops, when lines inside a loop statement have the same statement, this means that all those lines can be considered as the body of the loop.

Example:

#Python program to show how while loops work along with indentations
count = 0
while (count < 3):
count = count + 1
print (“Hello World”)

 

OUTPUT
Hello World
Hello World
Hello World

Using else statement with while loops

There is a clear similarity between if-else blocks and while loop blocks. As mentioned before, a while loop block executes until the loop condition is satisfied. Once the condition is satisfied, the loop terminates and breaks out. In the case of if-else statements, the if block is executed when the if statement is true. When the if statement is false, the program shifts to the else statement or block.

If Else Example:

if condition:
#these statements will be executed

else:
#these statements will be executed

While Loop Example
while condition
#these statements will be executed
else:
#execute these statements

Else statements in Combination with while loops

Else statements can also be combined with while loops. In those case, the body of the while loop is executed until the while loop condition is met. Once the condition is met, execution of the program shifts to the else block.

#Python example to show else statements in combination with while loops
count = 0
while (count < 3):
count = count + 1
print (“Hello World”)
else:
print (“Execution is now in the else block”)

 

OUTPUT
Hello World
Hello World
Hello World
Execution is now in the else block

Single Statement While Block

It can so happen that the while block you have coded just has one statement. In such cases, similar to the if block, the entire while loop along with the single line while loop body can be written in one line as follows:

#Python code to show that the while loop can be written down in one single line
count = 0
while (count == 0): print (“Hello World”)

Note

The loop written above is not recommended. From the loop termination statement, we can see that the value of the count will always be 0. Therefore, the loop will execute infinitely and never terminate. This is called an infinite loop and is not desired in your program. The only way to terminate this loop is to terminate it with the help of the compiler forcefully.

For in Loops

Sequential Traversal is when you are traversing elements of an ordered collection like a string or an array, or a list. In such cases, when you already know the number of iterations you want, it is recommended to use a for loop, which is the most common type of loop in Python. The for-in loops in Python are not similar to the for loops that many are accustomed to if using C or Java. The for-in loop structure here looks a lot like each loop in Java. The syntax for ‘for’ in loops are as follows:

Syntax:

for iterator_var in sequence:
statement(s)

Using the for in loop in a program

#Python Program to demonstrate how to use the 'for' in loop. Here the loop will be iterating over a #range of 0 to n-1

n = 4
for i in range (0, n):
print (i)

 

OUTPUT

0
1
2
3

How to iterate over a list of objects using a for in loop

#Python program to demonstrate how to iterate over a list of objects using a for in loop
print (“List Iteration”)
l = [“Hello”, “World”, “Python”]
for i in l:
print (i)

#Tuple iteration (immutable)
print (“\nTuple Iteration”)
t = (“Hello”, “World”, “Python”)
for i in t:
print (i)

#String Iteration
print (“\nString Iteration”)
s = “Hello”
for i in s:
print (i)

#Dictionary Iteration
print (“\n Dictionary Iteration”)
d = dict()
d[‘xyz’] = 123
d[‘abc’] = 345
for i in d:
print (“%s %d” %(i, d[i]))

 

OUTPUT
List Iteration
Hello
World
Python

Tuple Iteration
Hello
World
Python

String Iteration
H
e
l
l
o

Dictionary Iteration
xyz 123
abc 345

Iterating by Index of Sequences

Since we are using a List to iterate, lists are ordered collections, and the list elements are ordered. Therefore we can use the indices to iterate over ordered collections such as lists and arrays. The method here is first to calculate the length of the list and then use a range that is inside the limits of the list boundary to iterate.

#Python program to find out the length of a list and iterate using a suitable range
list = [“Hello”, “World”, “Python”]
for index in range (len (list)):
print list [index]

 

OUTPUT

Hello
World
Python

Using else Statement with for loops

Similar to while loops, an else statement can also be added to for loops. The only difference will be that for loops do not have an exit loop condition, so the else block will not be triggered by any exit condition. The else loop will only be executed after the for the block has finished execution.

#Python program to show that else and for in loops can be combined
list = [“Hello”, “World”, “Python”]
for index in range (len (list));
print list [index]
else:
print “Inside Else Block”

 

OUTPUT:

Hello
World
Java
Inside Else Block

Nested Loops

Nested Loops, as the name suggests, are loops inside loops. Python allows the implementation of nested loops. The syntax for the same is as follows:

Syntax:

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

Nested Loops can also be implemented in while loop structures as follows

Syntax:

while expression:
while expression:
statement(s)
statement(s)

Python does not differentiate between loops when it comes to nested loops. This means that any kind of loop can be written inside any kind of loop. A for loop can be inside a while loop and vice versa

#Python program to demonstrate how to implement nested loops
from_future_import print_function
for i in range (1, 5):
for j in range (i):
print (i, end = ‘ ’)
print()

 

OUTPUT
1
2 2
3 3 3
4 4 4 4

Loop Control Statements

Loop controls statements are statements that are used to disrupt the normal flow or execution of the loop. Python supports several loop control statements as follows:

Continue Statement

The continue statement is used when you want the current iteration to end and the execution of the loop to move to the next iteration.

#Python program to demonstrate how to use the continue statement
for letter in ‘helloworld’:
if letter == ‘h’ or letter == ‘s’:
continue
print ‘Current Letter :’, letter
var = 10

 

OUTPUT
Current Letter: e
Current Letter: l
Current Letter: l
Current Letter: o
Current Letter: w
Current Letter: o
Current Letter: r
Current Letter: l
Current Letter : d

Break Statement

Break Statements are used when you want to break out of the loop at any point during the execution of the loop. In simpler words, the break statement terminates the execution of the loop.

for letter in ‘helloworld’:
if letter == ‘h’ or letter == ‘s’:
break
print ‘Current Letter :’, letter

 

OUTPUT

Current Letter : h

Pass Statement

When you want to leave the body of the loop empty, then you can simply write pass. The pass statement can also be used to fill in empty functions as well as classes.

#Python program to demonstrate pass statement
for letter in ‘helloworld’:
pass
print ‘Last Letter :’, letter

 

OUTPUT

Last Letter : d

How For loops in Python work internally?

To understand how a for loop works in Python, you should first know the concept of Python Iterators. Let us start with a simple program in Python that uses a for a loop.

#Python program that uses a for loop

fruits = [“apple”, “orange”, “kiwi”]
for fruit in fruits:
print (fruit)

 

OUTPUT

apple
orange
kiwi

The program above demonstrates that for loops can iterate over collections or iterable objects. Fruits here is a list that contains the names of several fruits. Sets and dictionaries are also iterable objects but integer objects are not iterable objects. As mentioned before, iterable objects are lists, sets, dictionaries, tuples, or strings, and for loops can iterate over the elements present in these objects. Now let us look into the internal mechanism of how a for loop works:

  • Lists are already iterable but the first step is to make the collection iterable to be able to use the for loop. To do so, you can use the iter() function.
  • Thereafter, design a while loop that will execute infinite number of times and will only terminate if StopIteration is met.
  • Now inside the infinite loop, make a next block and fetch the next element on the fruits list.
  • Once the next element has been fetched, the said function is performed on the element. In this case, the function is to display the element: print (fruit).
#Python code to demonstrate the internal functionality of a for in loop
fruits = [“apple”, “orange”, “kiwi”]

#using the iter() method to create an iterable object. However, please not that list is already an #iterable object
iter_obj = iter (fruits)

#infinite while loop
while True:
try:
#using the next function, fetch the next element on the list
fruit = next (iter_obj)
print (fruit)
except StopIteration:

#If the StopIteration is met, then use a break statement to break out of the loop
break

 

OUTPUT

apple
orange
kiwi

 

Author

0 Comments

Submit a Comment

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.

Author