PYTHON TUTORIAL FOR BEGINNERS
Source: www.youtube.com/@RishabhMishraOfficial
Chapter - 15
Nested Loops in Python
• Nested Loops Definition
• Nested Loops Examples
• Nested Loops Interview Ques
Nested Loops in Python
Loop inside another loop is nested loop. This means that for every single time the outer
loop runs, the inner loop runs all of its iterations.
Why Use Nested Loops?
• Handling Multi-Dimensional Data: Such as matrices, grids, or lists of lists.
• Complex Iterations: Operations depend on multiple variables or dimensions.
• Pattern Generation: Creating patterns, such as in graphics or games.
Nested Loop Syntax
Syntax:
Outer_loop:
inner_loop:
# Code block to execute - inner loop
# Code block to execute - outer loop
P y t h o n N o t e s b y R i s h a b h M i s h ra
Nested Loop Example
Example: Print numbers from 1 to 3, for 3 times using for-for
nested loop
for i in range(3): # Outer for loop (runs 3 times)
for j in range(1,4):
print(j)
print()
Example: Print numbers from 1 to 3, for 3 times using while-
for nested loop
i = 1
while i < 4: # Outer while loop (runs 3 times)
for j in range(1, 4):
print(j)
print()
i += 1
Nested Loop Interview Question
Example: Print prime numbers from 2 to 10
for num in range(2, 10):
for i in range(2, num):
if num % i == 0:
break
else:
print(num)
Python Tutorial Playlist: Click Here
https://www.youtube.com/playlist?list=PLdOKnrf8EcP384Ilxra4UlK9BDJGwawg9
P y t h o n N o t e s b y R i s h a b h M i s h ra