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
Outer Loop:
for i in range(1, rows + 1): This loop runs from 1 to 5 (inclusive), representing the number of rows.
Inner Loop:
for j in range(i): For each iteration of the outer loop (each row), the inner loop runsitimes. This means:- When
iis 1, it prints 1 star. - When
iis 2, it prints 2 stars. - When
iis 3, it prints 3 stars, and so on.
- When
Print Statement:
print('*', end=' '): This prints a star followed by a space, andend=' '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!
