Can you explain nested loops with another example?

QuestionsQuestions4 SkillsProPython Control StructuresNov, 13 2025
0165

Certainly! Let's explore nested loops with an example that generates a pattern of stars (a simple triangle) using Python.

Example: Star Pattern

In this example, we'll create a right-angled triangle of stars. The outer loop will control the number of rows, while the inner loop will control the number of stars printed in each row.

rows = 5  # Number of rows for the triangle

for i in range(1, rows + 1):  # Outer loop for each row
    for j in range(i):  # Inner loop for printing stars
        print('*', end=' ')  # Print star without a new line
    print()  # Move to the next line after each row

Explanation

  1. Outer Loop:

    • for i in range(1, rows + 1): This loop runs from 1 to 5 (inclusive), representing the number of rows.
  2. Inner Loop:

    • for j in range(i): For each iteration of the outer loop (each row), the inner loop runs i times. This means:
      • When i is 1, it prints 1 star.
      • When i is 2, it prints 2 stars.
      • When i is 3, it prints 3 stars, and so on.
  3. Print Statement:

    • print('*', end=' '): This prints a star followed by a space, and end=' ' prevents moving to a new line after printing each star.
    • print(): This moves the cursor to the next line after finishing the inner loop for each row.

Output

The output of this code will be:

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

Summary

This example illustrates how nested loops can be used to create patterns and manage multiple dimensions of output. The outer loop controls the number of rows, while the inner loop determines how many stars to print in each row.

If you have any further questions or need more examples, feel free to ask!

0 Comments

no data
Be the first to share your comment!