What Are Loops In Python?

What Are Loops In Python?
What Are Loops In Python?

Introduction

Loops are an essential part of any programming language. Using loops, many complex programming logic can be reduced to a few lines of code. Loops are convenient when the same set of code is repeated multiple times; loops make the code readable and make the debugging process less tiring.

The sequence of execution of instructions in any programming language is sequential by default, i.e., one instruction is executed after the previous one has completed its execution. However, the sequence of execution can be modified as per requirements.

That is if the programmer wants to execute a set of instructions only if a condition is satisfied. For example, if a number is divisible by two then print that it’s an even number, else print that it’s an odd number. Such type of execution is called Selection based execution. 

In some cases wherein a statement or a group of statements is to be repeatedly executed multiple times, for example, generate all even numbers up to 1000, then this type of execution is called Repetition based control structure.

Python supports Selection and Repetition-based control Structure too. In general, Selection is used for decision-making and branching. Repetition based control structure is used for looping statements and iteration purposes. Read out the full blog for more details.

Sequential Execution vs Selection Based execution vs Repetition Based Execution

What is Loop?

Consider a situation wherein you need to print a statement or do some mathematical calculations multiple times in a row, i.e. the same set of statements need to be repeatedly executed. For example, consider the below program that prints even numbers from 2 to 20.

print("Generating all the even numbers from 2 to 20")
print("2")
print("4")
print("6")
print("8")
print("10")
print("12")
print("14")
print("16")
print("18")
print("20")

In the code above, we are manually listing down all the statements to be executed. The approach seems fine if we are to deal with a small set of statements. In the same example, if even numbers from 2 to 10000 are to be printed then doing this way will be quite cumbersome and time-consuming.

That’s where loops came into the picture. These ten lines of code can be easily shortened to two to three lines using Loops.

A real-life example of loops is the Software of ATM Machine, which repeatedly processes transaction after transaction until it runs out of cash.

In Programming Terminology, sometimes a particular piece of code needs to be executed multiple times in one go, which is called Iteration. There are two types of Iterations called Indefinite Iteration and Definite Iteration.

  • Definite Iteration: In this Iteration, a set of instructions is repeated a specific number of times. It is implemented using count-controlled loops such as for loops.
  • Indefinite: In this Iteration, a set of instructions is repeated until a condition is met. It is implemented using condition-controlled loops such as while loops.

A programming structure that implements Iteration is called a loop. A loop statement allows the execution of a statement or a group of statements multiple times. This type of control structure is called Repetition.

Why are Loops used?

The purpose of using loops in programming is to bridge the gap between sequential execution of instructions and to provide the capability of executing a statement or a group of statements multiple times using a single line of code.

Types of Loops in Python

Python programming language provides two types of loops to handle looping requirements, namely while and for loop, respectively. Apart from the syntax difference in the two, The while loop is used for indefinite Iteration, and for loop is used for definite Iteration.

While loop

Using a while loop, a set of statements can be executed repeatedly until a particular condition is satisfied. The while loop, in general, is used in cases of indefinite Iteration, and because it first evaluates the condition, it is called a pre-tested loop or condition-controlled loop.

Syntax:

 while (<expr>):
    	<statement(s)>

<statement> represents the block of code to be executed repeatedly. <expr> is the controlling expression and is evaluated first in Boolean context as follows:

If the condition is true

The flow of control moves inside the while loop and statements inside the while loop will be executed. The execution of <statement> continues until the <expr> becomes false at which point the program stops execution and proceeds to the first statement outside the loop body.

If the condition is false:

The flow of control will move outside of the while loop and the statement immediately next to the while loop will be executed. In general, a relevant variable has to be declared at the beginning of the while loop.

FlowChart of While Loop

Let’s try to understand the while loop with a simple python program to print numbers from 1 to 5.

num = 1  # initialization
while(num <= 5):  #expr -> num <= 5
    print(num)    # statement to be executed
    num += 1

In the above program, num <= 5 is the controlling expression to be tested first, and print(num), num += 1, are the statements to be executed.

The while loop can also be used in List; consider an example wherein a Python list is given, and we are required to print each item in the List. The following program will do the same:

demo_list = ['Java', 'Python','C']
while demo_list:   #controlling expression
    print(demo_list.pop())  # statement to be executed, .pop() is a method to remove items from a list

When a list is evaluated in a Boolean context, it is true if it has elements in it and false if it is empty. The .pop() method removes items from the List.

Single Statement while

If the while block consists of a single statement, the entire while loop can be declared in a single line.

count = 1
while (count): print('Exploring Loops in Python')
print("Out of the while loop")

This program will print, Exploring Loops an infinite number of times. It’s better not to try the above example because it will go to an infinite loop, and you have to press Ctrl+C keys to exit.

If there are multiple statements inside the while loop, the statements can be separated using (;). Consider the following program wherein a sequence of numbers from 9 to 0  is being printed using a single statement.

n = 10
while n > 0: n -= 1; print(n)

This only works for simple programs as two compound statements cannot be combined into one line. Also, PEP8 discourages multiple statements on one line. So it’s always a good idea to separate statements into multiple lines as it improves the readability of the code and is, in fact, a good practice to do so.

Using Else Statement with while

The statements inside the while loop are executed only when the controlling expression evaluates to true in the boolean context. An else statement can be used in combination with a while statement so that statements inside the else clause will be executed when the controlling expression evaluates to false in the while loop. This is, in fact, a unique feature of Python, not found in most other programming languages.

while <expr>:
	<statement>
else:
	<additional_statement>

Consider the following two programs:

N = 1
while N <= 6:
	print(N)
	N += 1
else:
	print(‘While Loop execution is done’)


Output:
1
2
3
4
5
6
While Loop execution is done
n = 0
while n < 6:
    n = n + 1
    if n == 5:
        break
    print(n)
else:
    print("Loop is finished")

Output:
1
2
3
4
Outside the while loop

In the first program, numbers from 1 to 6 are printed, and after that else clause is executed, i.e., the loop iterates until the controlling condition becomes false.

In the second program, numbers from 1 to 4 will be printed, and after that, the loop is terminated due to the break statement. That is due to the premature termination of the while loop, else the clause isn’t executed here. print statement outside the while loop is executed.

Explanation: Once the while loop terminates, the statements immediately after it are executed. The fundamental difference is that if an else statement is used in conjunction with a while statement, it will be executed only if the loop terminates by exhaustion.

If the loop is exited by any control structure like break and continue or if an exception is raised, the statements inside the else clause won’t be executed.

An excellent example of using an else clause with while is when an item is being been searched in the List. And we break out of the loop once the item is found, and the else clause contains the code which is to be executed if the item isn’t found.

A = ['ABC', 'DEF', 'GHI']
S = 'JKL'
 
i = 0
while (i < len(A)):
    if(A[i] == S):
        # processing for the item found
        break
    i += 1
else:
    # processing for the item not found
    print('Item not found')

Output:

Item not found

Infinite Loop

The execution of the while loop depends on the condition, which is evaluated in a boolean context first. A loop becomes an infinite loop if the condition never evaluates to false, and the while loop will theoretically continue to execute forever. 

Consider the following example:

while True:
    print('Infinite while loop')

The above program will print “Infinite while loop” infinitely. Generating an interrupt from the keyboard using Ctrl+C will terminate the program.

This is generally not used in simple programming applications. It is used in client/server programming and in cases where a semaphore is needed.

Note: while loop can be contained inside another while loop and while loops can also be nested inside if/elif/else statements and vice versa.

Nested While Loop

When a while loop is present inside another while loop, it is called a nested while loop. Consider the below example wherein a set of two numbers is being printed, depending on the condition specified in the while loop.

i = 5  
j = 10
 
 
# Example of nested while loop in Python
while i < 10:
    # This while loop is nested inside the previous while loop
    while j < 15:
        print(i, j)
        j += 1
        i += 1 

In the case of nested while loop, first the condition specified in the outer while loop is checked, if it evaluates to true then the control moves to the inner while loop which executes the statements as long as the inner while loop condition is true.

For Loops

For loops in Python are used for definite Iteration wherein a sequential traversal needs to be done, for example traversing an integer array. It’s also called collection-based Iteration. For loops can only be used in iterable objects. Because of the fact that it is executed a finite number of times, it is also called a count-controlled loop.

Syntax:

for <iterator_variable> in sequence:
	<statement>

Before understanding how a for loop works internally, let’s briefly go through all the terminologies:

TerminologyExplanation
IterationProcess of looping through the objects in a collection
IterableAn object over which Iteration is to be done
IteratorAn object that produces successive items from its associated iterable
iter()A python built-in function that is used to obtain an iterator from iterable

Consider an example of for loop:

# for loop example
demo = ['ABC','DEF','GHI']  # A list in Python
 
for i in demo:
    print(i)
print('Outside for loop')

This will print ABC, DEF, and GHI in separate lines. Internally the for-loops work as follows. 

  • Firstly an iterator (say itr) of the collection demo to be is obtained using iter() method.
itr = iter(demo)
  • An infinite while loop is run and the built-in next() function obtains the nest value from the iterator. An iterator maintains its state internally so when next() method is called, it knows what values have been already iterated over.
  • The infinite while loop stops only when the StopIteration exception is raised.

To better understand the internal working of the loop, open the command prompt and type ‘Python’. This will open Python Interpreter in Interactive mode in your command prompt. 

  • And then create a Python List, demo = [‘ABC’, ‘DEF’, ‘GHI’]
  • Create an iterator over the list using itr = iter(demo). This will create an iterable object of the list.
  • Now repeatedly call, next(itr) until the StopIteration Exception is raised.

The flow of execution can be understood using the below diagram as well.

Iterating on Lists or Similar Constructs

For loop can also be used to iterate through a List, Tuple, String, and Dictionary as follows:

# for loop iteration
 
# Iterating over a list of strings
print("Iterating over List")
demo_list = ["a", "b", "c", "d"]
for i in demo_list:
    print(i)
 
 
# Iterating over a tuple
print("\nIterating over Tuple")
demo_tuple = ("a", "b", "c", "d")
for i in demo_tuple:
    print(i)
 
 
# Iterating over a dictionary
print("\nIterating over Dictionary")
demo_dict = {"a": 1, "b": 2, "c": 3, "d": 4}
for i in demo_dict:
    print(i)
    print(demo_dict[i])
 
# Iterating over a String
print("\nIterating over String")
demo_string = "Hello World"
for i in demo_string:
    print(i)

Using Range() Function

Python’s built-in range function can be used to generate a sequence of numbers from 0 by default up to a specified range.

range(start, stop, step) -> start is the starting point of the range, stop is the ending point and step is an optional argument specifying the increment value.

Python for loop can be used in combination with range() function as follows:

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

Iterating on Indices of List

An alternative way to iterating through each item is by using Sequence Index using the ‘in’ keyword. The len() function returns the length of the List and when the range() function is applied to it, indices of the List on range object are returned.

list = ["Coding Ninjas", "Code Studio", "Code Zen"]
for index in range(len(list)):
    print(list[index])

Using else statement with for

An else statement can be combined with a ‘for’ loop as well. Just like with the ‘while’ loop, here also the else statement will execute when the for loop will exhaust by iterating over the List.

demo_list = ['ABC','DEF','GHI']
for i in range(len(demo_list)):
    print(demo_list[i])
 
else:
    print("for loop has finished execution, else block is now executed")

Nested for Loop

A for loop can also be nested inside another for a loop. In this case, The “inner loop” will be executed one time for each iteration of the “outer loop”.

# Output
# *
# **
# ***
# ****
# *****
 
# Nesting of for loops in Python
 
# Outer Loop
for i in range(0, 5):
 
    # Inner Loop
    for j in range(0, i+1):
        print("*", end="")
    
    print("")

The output of the code will be a triangular pyramid of five rows.

Loop Control Statements

The default execution of any program in Python is sequential. Using Loops can alter the sequential execution to Repetitive Execution. However, there are cases where the flow of a loop needs to be altered, sometimes the current Iteration of the loop needs to be terminated.

The break and continue statements are used in such cases. When execution leaves a scope, all automatic objects that were created in that scope are destroyed.

Break

It terminates the loop containing it. Control of the program goes to the statement immediately after the body of the loop.

for i in sequence:
    # statement to be executed inside for loop
 
    # if this condition is true, then break the loop
    if condition:
        break
    # statement to be executed inside for loop
 
 
while <expression>:
    # statement to be executed inside while loop
    if<condition>:
        break
    # statement to be executed inside while loop

Consider the following program wherein a string is iterated over using the ‘for’ loop. The program will break once the character is N.

s = 'CodingNinjas'
for i in s:
    
    # statement to be executed inside for loop
    print(i)
    if i == 'N':
break
 
print('Current Letter', i)

In short, the break statement actually brings control out of the loop, and all the objects that were created as part of that scope are deleted. Also, if the break statement is used inside a nested loop, it terminates the innermost loop, and the control shifts to the next statement in the outer loop.

Continue

Whenever the Python interpreter encounters, ‘continue’ statement inside a loop, it will skip the execution of the rest of the statements in that Iteration and will bring the control to the beginning of the loop. Continue does not terminate or exit out of the loop rather it continues with the next Iteration.

Consider the below program wherein a sequence of characters in the String, “CodingNinjas” will be printed except the character N using a continue statement.

for i in "CodingNinjas":
    if i == "N":
        continue
    print(i)

The fundamental difference between Break and Continue statements can be understood using the following:

Pass

Pass statement in the loop is generally used to write empty loops; it is used for empty control structure, function, and classes. Generally, it is used in situations wherein a piece of code is not yet implemented but needs to be implemented in the near future.

# usage of continue
for i in "Loops in Python":
    pass
print(i)

Frequently Asked Questions

What are the three types of loops in Python?

There are three types of Loops, namely
1. While loop
2. For loop
3. Nested Loop

What are loops in Python?

Loop is a programming structure that implements the concept of Iteration. Loop in Python is used to execute a statement or a group of statements multiple times.

How does for loop work in Python?

The for loop in Python works like an iterator method as described below:-
1. Firstly, an iterator (say itr) of the collection is obtained using the iter() method.
2. An infinite while loop is run and is stopped only when the StopIteration exception is raised as follows -The built-in function next() is used to obtain the next value from the iterator. An iterator maintains its state internally, so when the next() method is called, it knows what values have been already iterated over.

What are the three parts of a for loop?

Generally, a for loop consists of three main parts i.e.
1. Initialisation: Initialising the value from where the looping statement has to begin its execution.
2. Condition: The condition which needs to be satisfied to execute the statements inside the loop
3. Updating: Updating the initialized value

What is a Loop example?

Whenever a statement or a group of statements is to be executed multiple times, a loop is used. Consider the following example wherein Hello World is being printed ten times using a loop.

for(int i = 0; i < n; i++)
{
printf(“%d”, i)
}
In the example above, int i = 0 is the initialization; i < n is the condition and i++ is updation.
printf(“%d”, i) is the statement to be executed

i = 0
for i in range(10):
print(“Hello World”)

Key Takeaways

This blog attempted to give a thorough explanation of the various loops in Python with the help of multiple examples. Loops play an essential role in any programming language.

In interview questions, too, the knowledge of loops is convenient. Questions can be asked combining the understanding of loops and conditional statements like the FizzBuzz program.

Now you have a thorough understanding of loops, so don’t stop here. Try out your knowledge of loops with the help of these questions.

Do check out the Guided Path to learn more about Python in-depth.

By Manvi Chaddha