Understanding Nested Loops in Python with Logic Building
This article is a complementary resource to the Learn Python Basics course.
This article is a complementary resource to the Learn Python Basics course.
A nested loop is a loop inside another loop. For example,
# List of car attributes
attributes = ['Electric', 'Fast']
# List of car brands
cars = ['Tesla', 'Porsche']
# Outer loop: Iterating through each attribute
for attribute in attributes:
# Inner loop: Iterating through each car brand
for car in cars:
print(attribute, car)
Output
Electric Tesla Electric Porsche Fast Tesla Fast Porsche
Here,
attributes
list. It first picks
'Electric'
, then
'Fast'
.cars
list. In this case, it goes through
'Tesla'
and
'Porsche'
for each attribute.Nested loops are useful for printing patterns like squares or triangles and help in building logical thinking. Let's see how they work.
Let's say you want to print a star pattern like follows:
* * * * * * * * *
To create this pattern, we will use nested loops:
Think about the stars in each row:
Think about the number of rows:
Code Implementation:
# Outer loop: Controls how many rows (or lines) to print (3 rows)
for i in range(3):
# Inner loop: Controls how many stars to print in each row (3 stars per row)
for j in range(3):
print("*", end=" ") # Print a star on the same line
# Move to the next line after printing 3 stars in the row
print()
Notice that:
end=" "
keeps the stars on the same line by adding a space instead of moving to the next line.print()
without any arguments moves the cursor to the next line after completing each row.A right-angled triangle has one side that increases in length with each row:
* * * * * * * * * * * * * * *
Now, let's build logic to create a right-angled triangle.
Think about the stars in each row:
This means the number of stars printed in each row increases with each new row.
Think about the number of rows:
The inner loop controls stars per row:
i
).Code Implementation:
height = 5
for i in range(1, height + 1): # Outer loop for rows
for j in range(i): # Inner loop for printing stars
print("*", end=" ")
print() # Moves to the next line
Output
* * * * * * * * * * * * * * *
An inverted right-angled triangle starts with the widest base and reduces the number of stars in each row:
* * * * * * * * * * * * * * *
Think about the stars in each row:
This means the number of stars decreases with each new row.
Think about the number of rows:
The inner loop controls stars per row:
i
times, where
i
is the current row number.Code Implementation:
height = 5
for i in range(height, 0, -1): # Outer loop for rows (starting from height)
for j in range(i): # Inner loop for printing stars
print("*", end=" ")
print() # Moves to the next line
Output
* * * * * * * * * * * * * * *
Here, the outer loop
for i in range(height, 0, -1)
starts at
5
and decreases to
1, controlling the number of rows.
A hollow square has stars on the border, with spaces inside:
* * * * *
* *
* *
* *
* * * * *
Now, let's build logic to create a hollow square.
Think about the stars in each row:
Think about the number of rows and columns:
Logic for printing stars or spaces:
*
) for the first and last rows (i == 0 or i == size - 1
).j == 0 or j == size - 1
).Code Implementation:
size = 5
for i in range(size): # Outer loop for rows
for j in range(size): # Inner loop for columns
if i == 0 or i == size - 1 or j == 0 or j == size - 1:
print("*", end=" ") # Print stars on the border
else:
print(" ", end=" ") # Print spaces inside
print() # Moves to the next line
Output
* * * * *
* *
* *
* *
* * * * *
Here, the inner loop
for j in range(size)
determines if the cell is a border.
If the cell is in the first/last row (i == 0
or
i == size - 1
) or the first/last column (j == 0
or
j == size - 1
), it prints a star (*
) . Otherwise, it prints a space.
Nested loops are a versatile tool in Python for solving pattern-based problems and working with multi-dimensional data!
Nested loops are computationally heavy, especially for larger patterns. However, Python provides simple alternatives to create patterns without nested loops.
Let's look at an example.
Square Pattern:
n = 5
for i in range(n):
print('*' * n)
Output
***** ***** ***** ***** *****
Triangle Pattern:
n = 5
for i in range(1, n + 1):
print('*' * i)
Output
* ** *** **** *****
These methods are more efficient as they leverage Python's string multiplication, reducing the overhead of nested iterations.
While nested loops are great for understanding the structure, these approaches are cleaner and faster for generating patterns in Python.
Can you write a program to print a full pyramid pattern using nested loops?
This will be a great way to understand how nested loops work. You'll gain a strong understanding of how to use nested conditions effectively.