Skip to content

script_13.py - Nested Loop Pattern Printer

Code

Python
#!/usr/bin/env python3
"""Nested loop pattern printer"""

rows = int(input("Enter number of rows: "))

for i in range(1, rows + 1):
    for j in range(1, i + 1):
        print("*", end="")
    print()

Explanation

Line 4: rows = int(input("Enter number of rows: ")) - rows is integer, controls outer loop iterations

Line 6: for i in range(1, rows + 1): - Outer loop iterates from 1 to rows - i represents current row number - Controls how many iterations of inner loop

Line 7: for j in range(1, i + 1): - Inner loop (nested inside outer loop) - Iterates from 1 to i (current row number) - j represents position in current row - Number of iterations increases each outer iteration - Row 1: prints 1 star, Row 2: prints 2 stars, etc.

Line 8: print("*", end="") - end="" parameter changes default newline to empty string - Prevents automatic line break after each print - Allows printing multiple stars on same line - Stars print horizontally

Line 9: print() - No arguments = prints just a newline - Not indented under inner loop, but under outer loop - Executes after inner loop completes - Moves to next line for next row - Creates the pattern structure