How to Print Rectangles with Nested Loops in Python
This guide explains how to use nested loops in Python to print a rectangle of characters (like asterisks) to the console. We'll cover the basic logic and how to create a reusable function.
Basic Rectangle Printing with Nested Loops
The core concept is to use two nested for
loops:
- The outer loop controls the rows.
- The inner loop controls the columns (characters within each row).
num_rows = 2
num_cols = 3
for _ in range(num_rows): # Outer loop: rows
for _ in range(num_cols): # Inner loop: columns
print('*', end=' ') # Print an asterisk and a space
print() # Move to the next line after each row
Output:
* * *
* * *
for _ in range(num_rows):
: This loop iteratesnum_rows
times. We use_
as the loop variable because we don't actually need the loop counter value itself, just the repetition.for _ in range(num_cols):
: This inner loop iteratesnum_cols
times for each row. Again, we use_
because we don't need the counter.print('*', end=' ')
: This prints an asterisk followed by a space. Theend=' '
is crucial; it preventsprint()
from adding a newline, so the asterisks for a single row stay on the same line.print()
: This emptyprint()
statement adds a newline after each row has been printed. Without this, you'd get all the asterisks on a single line.
Creating a Reusable Function
It's good practice to encapsulate this logic in a function:
def print_rectangle(num_rows, num_cols):
for _ in range(num_rows):
for _ in range(num_cols):
print('*', end=' ')
print() # Newline after each row
print_rectangle(2, 3)
print()
print_rectangle(3, 4)
print()
print_rectangle(4, 5)
Output:
* * *
* * *
* * * *
* * * *
* * * *
* * * * *
* * * * *
* * * * *
* * * * *
- The function now takes
num_rows
andnum_cols
as arguments, making it reusable for different rectangle sizes. - The logic inside the function is identical to the previous example.