Loops in Python
Loops in Python are used to repeat actions efficiently. The main types are For loops (counting
through items) and While loops (based on conditions).
While Loop in Python
In Python, a while loop is used to execute a block of statements repeatedly until a given
condition is satisfied. When the condition becomes false, the line immediately after the loop in
the program is executed.
Python While Loop Syntax:
while expression:
statement(s)
All the statements indented by the same number of character spaces after a programming
construct are considered to be part of a single block of code. Python uses indentation as its
method of grouping statements.
Example of Python While Loop:
cnt = 0
while (cnt < 3):
cnt = cnt + 1
print("Hello United University")
Output
Hello United University
Hello United University
Hello United University
Using else statement with While Loop in Python
Else clause is only executed when our while condition becomes false. If we break out of the
loop or if an exception is raised then it won't be executed.
Syntax of While Loop with else statement:
while condition:
# execute these statements
else:
# execute these statements
1|Page
Example:
The code prints "Hello United University" three times using a 'while' loop and then after the
loop it prints "In Else Block" because there is an "else" block associated with the 'while' loop.
cnt = 0
while (cnt < 3):
cnt = cnt + 1
print("Hello United University ")
else:
print("In Else Block")
Output
Hello United University
Hello United University
Hello United University
In Else Block
Infinite While Loop in Python
If we want a block of code to execute infinite number of times then we can use the while loop
in Python to do so.
The code given below uses a 'while' loop with the condition (count == 0) and this loop will
only run as long as count is equal to 0. Since count is initially set to 0, the loop will execute
indefinitely because the condition is always true.
count = 0
while (count == 0):
print("Hello United University ")
Note: It is suggested not to use this type of loop as it is a never-ending infinite loop where the
condition is always true and we have to forcefully terminate the compiler.
2|Page
For Loop in Python
For loops are used for sequential traversal. For example: traversing a list or string or array etc.
In Python, there is "for in" loop which is similar to foreach loop in other languages. Let us learn
how to use for loops in Python for sequential traversals with examples.
For Loop Syntax:
for iterator_var in sequence:
statements(s)
n=4
for i in range(0, n):
print(i)
Output
0
1
2
3
Explanation: This code prints the numbers from 0 to 3 (inclusive) using a for loop that iterates
over a range from 0 to n-1 (where n = 4).
Example with List, Tuple, String, and Dictionary Iteration Using for Loops in Python
We can use for loop to iterate lists, tuples, strings and dictionaries in Python.
li = ["United", "is", "University"]
for i in li:
print(i)
Output
United
is
University
3|Page
Iterating by the Index of Sequences
We can also use the index of elements in the sequence to iterate. The key idea is to first calculate
the length of the list and in iterate over the sequence within the range of this length.
list = ["United", "is", "University"]
for index in range(len(list)):
print(list[index])
Output
United
is
University
Explanation: This code iterates through each element of the list using its index and prints each
element one by one. The range(len(list)) generates indices from 0 to the length of the list minus
1.
Using else Statement with for Loop in Python
We can also combine else statement with for loop like in while loop. But as there is no condition
in for loop based on which the execution will terminate so the else block will be executed
immediately after for block finishes execution.
list = ["United", "is", "University"]
for index in range(len(list)):
print(list[index])
else:
print("Inside Else Block")
Output
United
is
University
Inside Else Block
Explanation: The code iterates through the list and prints each element. After the loop ends it
prints "Inside Else Block" as the else block executes when the loop completes without a break.
4|Page
Nested Loops in Python
Python programming language allows to use one loop inside another loop which is
called nested loop. Following section shows few examples to illustrate the concept.
Nested Loops Syntax:
for iterator_var in sequence:
for iterator_var in sequence:
statements(s)
statements(s)
The syntax for a nested while loop statement in the Python programming language is as
follows:
while expression:
while expression:
statement(s)
statement(s)
A final note on loop nesting is that we can put any type of loop inside of any other type of loops
in Python. For example, a for loop can be inside a while loop or vice versa.
from __future__ import print_function
for i in range(1, 5):
for j in range(i):
print(i, end=' ')
print()
Output
1
22
333
4444
Explanation: In the above code we use nested loops to print the value of i multiple times in
each row, where the number of times it prints i increases with each iteration of the outer loop.
The print() function prints the value of i and moves to the next line after each row.
5|Page
Loop Control Statements
Loop control statements change execution from their normal sequence. When execution leaves
a scope, all automatic objects that were created in that scope are destroyed. Python supports
the following control statements.
Continue Statement
The continue statement in Python returns the control to the beginning of the loop.
for letter in 'unitedisuniversity':
if letter == 'e' or letter == 's':
continue
print('Current Letter :', letter)
Output
Current Letter : u
Current Letter : n
Current Letter : i
Current Letter : t
Current Letter : d
Current Letter : u
Current Letter : n
Current Letter : i
Current Letter : v
Current Letter : r
Current Letter : i
Current Letter : t
Current Letter : y
Explanation: The continue statement is used to skip the current iteration of a loop and move to
the next iteration. It is useful when we want to bypass certain conditions without terminating
the loop.
6|Page
Break Statement
The break statement in Python brings control out of the loop.
for letter in ' unitedisuniversity ':
if letter == 'e' or letter == 's':
break
print('Current Letter :', letter)
Output
Current Letter : e
Explanation: break statement is used to exit the loop prematurely when a specified condition
is met. In this example, the loop breaks when the letter is either 'e' or 's', stopping further
iteration.
Pass Statement
We use pass statement in Python to write empty loops. Pass is also used for empty control
statements, functions and classes.
for letter in ' unitedisuniversity ':
pass
print('Last Letter :', letter)
Output
Last Letter : y
Explanation: In this example, the loop iterates over each letter in ' unitedisuniversity ' but
doesn't perform any operation, and after the loop finishes, the last letter ('y') is printed.
7|Page