script_23.py - Nested Loops for Matrix
Code
#!/usr/bin/env python3
"""Nested loops for matrix"""
rows = 3
cols = 4
for i in range(rows):
for j in range(cols):
print(f"({i},{j})", end=" ")
print()
Explanation
Line 4-5: Constants
- rows = 3 defines number of rows (integer literal)
- cols = 4 defines number of columns (integer literal)
Line 7: for i in range(rows):
- Outer loop iterates 3 times (0, 1, 2)
- i represents row index
- Each iteration processes one row
Line 8: for j in range(cols):
- Inner loop (nested inside outer)
- Iterates 4 times per outer iteration (0, 1, 2, 3)
- j represents column index
- Total iterations: 3 × 4 = 12
Line 9: print(f"({i},{j})", end=" ")
- Prints coordinate pair
- end=" " adds space instead of newline
- Keeps items on same line
- Both i and j are in scope (i from outer, j from inner)
Line 10: print()
- Indented under outer loop, not inner loop
- Executes after inner loop completes
- Prints newline to move to next row
- Creates matrix layout: