Understanding Nested Loops in Python with Logic Building

This article is a complementary resource to the Learn Python Basics course.

Understanding Nested Loops in Python with Logic Building

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,

  • The outer loop iterates over the attributes list. It first picks 'Electric', then 'Fast'.
  • For each iteration of the outer loop, the inner loop runs through all the items in the 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.


Building Square Pattern

Let's say you want to print a star pattern like follows:

* * *  
* * *  
* * *  

To create this pattern, we will use nested loops:

  • The outer loop controls the number of rows (one for each line).
  • The inner loop controls how many stars are printed in each row.

Think about the stars in each row:

  1. You need 3 stars in each row.
  2. This means the inner loop will run 3 times for each row.

Think about the number of rows:

  1. You need 3 rows (so the outer loop will run 3 times, one for each row).

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.

Building Right-Angled Triangle Pattern

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:

  • In the first row, you need 1 star.
  • In the second row, you need 2 stars.
  • In the third row, you need 3 stars, and so on.

This means the number of stars printed in each row increases with each new row.

Think about the number of rows:

  • You need 5 rows (one for each line from 1 star to 5 stars).
  • The outer loop will run 5 times, once for each row.

The inner loop controls stars per row:

  • In the first row, you print 1 star.
  • In the second row, you print 2 stars.
  • The inner loop will run as many times as the current row number (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

* 
* * 
* * * 
* * * * 
* * * * * 

Building Inverted Right-Angled Triangle Pattern

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:

  • In the first row, you need 5 stars.
  • In the second row, you need 4 stars.
  • In the third row, you need 3 stars, and so on.

This means the number of stars decreases with each new row.

Think about the number of rows:

  • You need 5 rows (one for each line).
  • The outer loop will run 5 times, starting from 5 and decreasing to 1.

The inner loop controls stars per row:

  • In the first row, you print 5 stars.
  • In the second row, you print 4 stars, and so on.
  • The inner loop will run 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.


Hollow Square

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:

  • The first and last rows have stars all the way across.
  • The middle rows have stars at the beginning and end, with spaces in between.

Think about the number of rows and columns:

  • You need a square with size x size dimensions.
  • The outer loop controls the rows, and the inner loop controls the columns.

Logic for printing stars or spaces:

  • Print stars (*) for the first and last rows (i == 0 or i == size - 1).
  • Print stars at the borders (first and last columns) for middle rows (j == 0 or j == size - 1).
  • Otherwise, print spaces.

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.


Takeaways

  • Nested loops allow you to work with multi-dimensional structures, making them ideal for creating grids and patterns.
  • The outer loop controls the number of iterations of the inner loop.
  • By combining conditions and loops, you can create complex shapes like squares, triangles, and hollow patterns.

Nested loops are a versatile tool in Python for solving pattern-based problems and working with multi-dimensional data!


Optimized Methods for Patterns in Python

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.