Loops in Python are a fundamental concept that allow you to execute a block of code multiple times. In program logic, there comes multiple scenarios where we need to iterate over all the elements of a collection datatype. Those iterations over a collection can be done using loops.
Loops in Python
Python supports two types of loops: for
loop and while
loop
for
loop
for
loop in Python is used to iterate over a elements of a collection sequence (list, tuple, string, set, dictionary or other iterable objects). for
loop allows to execute a block of code repeatedly for each element in the sequence. We can also use conditional statements, operators within that block of code.
for variable in sequence:
# Code block to execute
variable
–for
loop variable takes the value of the current item in the sequence.sequence
– This is the iterable sequence to iterate over. This sequence can be a collection datatype, string.
for
loop Example
course_list = ['Python', 'AWS', 'Java', 'Azure', 'Data Science']
for course in course_list:
print(course)
for
loop with range()
method and if
statement
for number in range(10):
if number % 2 == 0:
print(number)
range()
method generates number from 0 to the given number. Using for
loop we are iterating over the range of numbers and execute the code block for each number. if
condition checks for remainder when number divided by 2 and if remainder is 0 then print that number.
Program Output
0
2
4
6
8
for
loop with string
for letter in "shbytes":
print(letter)
s
h
b
y
t
e
s
for
loop with dictionary
print("dictionary iteration")
courses = {"c1": "Python", "c2": "AWS", "c3": "Azure", "c4": "Java"}
for key in courses:
print("key - ", key, "value - ", courses[key])
In this program, we have defined a dictionary courses
. Dictionary elements are key-value pairs. Using for
loop we are iterating over the dictionary elements. We will get the key
of each dictionary element and courses[key]
we get the value of that key
.
Program Output
dictionary iteration
key - c1 value - Python
key - c2 value - AWS
key - c3 value - Azure
key - c4 value - Java
In the similar way, we can iterate over other collection datatypes like Tuple and Set.
for
loop with else
statement
An else
block can be used with a for
loop. The code in the else
block runs after the loop completes its iteration, unless the loop is terminated with a break
.
for variable in sequence:
# Code block to execute
else:
# Code block for else
for
loop will iterate over the sequence and will execute the code block for all elements.else
code block will be executed after thefor
loop completes its iteration.else
code block will not be executed, iffor
loop is exited usingbreak
command infor
loop code.
for
loop with else
Example course_tuple = ('Python', 'Java', 'Data Science')
for course in course_tuple:
print(course)
else:
print("for loop completed")
Program Output
Python
Java
Data Science
for loop completed
while
Loop
while
loop in Python works with a specified condition and repeatedly execute a block of code as long as the given condition is True
. while
loop is particularly useful when the number of iterations is not known beforehand and the loop continues to run till the particular condition is True
.
# initialize variable
while condition:
# Code to execute repeatedly
# update variable
variable
– Define avariable
on whichwhile
loop condition will be checked. Initializevariable
with initial value.condition
– This is an expression usingvariable
, that evaluates toTrue
orFalse
.while
loop continues running as long as this condition isTrue
.- Block of code – This is the code block that will be executed repeatedly as long as the
while
loop condition isTrue
- update
variable
– Update variable for next iteration.
while
loop
Example – counter = 0
while counter < 6:
print("Counter value is", counter)
counter += 1
In this program, we have defined a variable counter
. We are using while
loop with condition counter < 6
. If this condition is True
, then while
loop code block will be executed. As a code block, we will print the current counter
value and increase the counter
value by 1. Based on the update counter
value, again while
loop condition will be checked and will repeat the steps till condition is True
. while
loop condition will remain True
, till counter value reached 6.
Program Output – while
loop
Counter value is 0
Counter value is 1
Counter value is 2
Counter value is 3
Counter value is 4
Counter value is 5
Nested loop
Similar to nested for
loop, nested while
loop can be used. We can have any level of nested loops. At 1 level of nested hierarchy, we can create 4 combinations using for
loop and while
loop.
for
loop insidefor
loopwhile
loop insidefor
loopwhile
loop insidewhile
loopfor
loop insidewhile
loop
for
loop inside for
loop
We can have for
loop inside another for
loop. We can use any level of nested for
loops.
for variable in sequence:
# Code block 2 to execute outer for loop
for variable_inner in sequence_inner:
# Code block to execute inner for loop
# Code block 2 to execute outer for loop
for
loop inside for
loop
Example – print("Nested for loop")
for i in range(3):
for j in range(2):
print(f"i = {i}, j = {j}")
In this program, we are using for
loop with variable i
and elements from range(3)
. Inside this for
loop, there is another for
loop with variable j
and elements from range(2)
. For each value of i
, complete iteration of inner for
loop with j will be executed.
Program Output – for
loop inside for
loop
Nested for loop
i = 0, j = 0
i = 0, j = 1
i = 1, j = 0
i = 1, j = 1
i = 2, j = 0
i = 2, j = 1
while
loop inside while
loop
# initialize variable_1
while condition_1:
# Code to execute repeatedly
# initialize variable_2
while condition_2:
# inner loop - code to execute repeatedly
# update variable_2
# update variable_1
- For each iteration of outer
while
loop, complete iteration of innerwhile
loop will be executed.
while
loop inside while
loop
Example – counter_1 = 0
while counter_1 < 3:
counter_2 = 0
while counter_2 < 2:
print("counter_1 is", counter_1, "and counter_2 is", counter_2)
counter_2 += 1
counter_1 += 1
In this program, outer while
loop condition is based on variable counter_1
and inner while
loop condition is based on variable counter_2
. For each iteration of outer while
loop, complete inner while
loop will be executed. We will print the value of variables counter_1
and counter_2
.
Program Output – while
loop inside while
loop
counter_1 is 0 and counter_2 is 0
counter_1 is 0 and counter_2 is 1
counter_1 is 1 and counter_2 is 0
counter_1 is 1 and counter_2 is 1
counter_1 is 2 and counter_2 is 0
counter_1 is 2 and counter_2 is 1
Nested loops combinations
for
loop and while
loop can be used with each other to create a nested loops. There are 4 combinations (for 1 level of nested) that can be created as nested loops.
- for loop inside for loop
- while loop inside for loop
- while loop inside while loop
- for loop inside while loop
Infinite loops
Any loop can run indefinitely, if the given condition never becomes False. In case of while
loop, if the given condition never becomes False
then while
loop can run indefinitely. This is called an infinite loop.
# initialize variable
while True:
# Code to execute repeatedly
# update variable
If we notice in this code, while
loop condition is True
always. Since, this while
loop condition will never become False
and it will run indefinitely.
Problems with Infinite loop
- If the loop will keep on running indefinitely, then program execution will not move forward and will stuck a particular code
- Indefinite loop execution will consume the high memory and CPU resources, which can cause program to fail.
Uses of Infinite loop
- Infinite loops are used in scenarios where we don’t know the condition or the condition are dynamic, that keeps on changing based on the code block execution.
- Infinite loops are also used in monitoring or health check scenarios, where program continuously checks for application health status.
To stop an infinite loop, we can use a break
statement, or manually interrupt the program (e.g., with Ctrl + C
in most environments).
loop control statements
Python provides three loop control statements – break
, continue
, and pass
. These statements are used to control the flow of loops and other blocks of code. Each of these statement serves a specific purpose in managing how loops operate or how blocks of code are executed.
break
Statement
break
statement in Python is used to exit a loop prematurely.- Whenever a
break
statement is encountered inside a loop, the loop is immediately terminated, and the program continues with the next statement after the loop. break
statement can be used with bothfor
loop andwhile
loop.
for num in range(8):
if num == 5:
break # Exit the loop when num is 5
print(num)
In this program, we are using for
loop to iterate through the elements from range()
method. if
condition check for num == 5
. if num
value is 5, then break
statement will be executed. break
statement will stop the execution of the for
loop and exit from for
loop. Values will be printed from 0 to 4.
Program Output – break
Statement
0
1
2
3
4
continue
Statement
continue
statement is used to skip the rest of the code inside the loop for the current iteration and move on to the next iteration.- Unlike
break
, it doesn’t terminate the loop but rather skips only the current iteration and moves to the next iteration.
for num in range(6):
if num == 2:
continue # Skip the iteration when num is 2
print(num)
In this program, we are using for
loop to iterate through the elements from range()
method. if
condition check for num == 2
. if num
value is 2, then continue
statement will be executed. continue
statement will skip the current iteration of for loop and will move on to next iteration. It means it will skip printing of value 2 and will print all other values from 0 to 5.
Program Output – continue
Statement
0
1
3
4
5
pass
Statement
pass
statement is a placeholder that does nothing when executed.- It is used in situations where a statement is syntactically required, but you do not want to execute any code.
pass
statement does not stop or skip any iteration of the loop.- It is often used in empty classes, functions, or conditional blocks as a temporary placeholder.
for num in range(4):
if num == 2:
pass # Do nothing, just pass
print(num)
Program Output – pass
Statement
0
1
2
3
Summary
In this article, we learned about for loop while loop and explored different scenarios with loops. We also explored loop control statements break, continue and pass.