- Draw patterns using nested
forloops (rows = outer, stars per row = inner). - In Python you can often use STRING MULTIPLICATION instead:
"* " * 5gives five stars (with space). - Full block: 5 rows, 5 stars each β
for i in range(5): print('* ' * 5). - Triangle (1, 2, 3, 4, 5 stars):
for i in range(1, 6): print('* ' * i). - Inverted triangle (5, 4, 3, 2, 1):
for i in range(5, 0, -1): print('* ' * i).
Letβs go! π
Part 1: String Multiplication
π In Python you can multiply a string by an integer β it repeats the string.
"*" * 3 β "***"
"* " * 5 β "* * * * * " (star + space, 5 times)
So to print 5 stars (with space between), you can simply do: print('* ' * 5). No need for a loop just to print the same thing 5 times!
Demo:
print(" Demo: '*' * 5 =", repr("*" * 5))
print(" Demo: '* ' * 5 =", repr("* " * 5))
Part 2: Full Block (5 Rows Γ 5 Stars)
π Nested loop way:
for i in range(5): # 5 rows
for j in range(5): # 5 stars per row
print("*", end=" ")
print()
π Simpler way (one loop + string multiply):
for i in range(5):
print("* " * 5)
Each row is the same: "* " repeated 5 times.
Demo: 5Γ5 block (simple way)
for i in range(5):
print(" " + "* " * 5)
Part 3: Triangle (1, 2, 3, 4, 5 Stars)
π Row 1: 1 star, row 2: 2 stars, row 3: 3 stars, ... Number of stars = row number.
for i in range(1, 6):
print("* " * i)
(i = 1 β 1 star, i = 2 β 2 stars, ..., i = 5 β 5 stars)
Demo: Triangle (1 to 5 stars)
for i in range(1, 6):
print(" " + "* " * i)
Part 4: Inverted Triangle (5, 4, 3, 2, 1)
π First row 5 stars, then 4, 3, 2, 1. Use range(5, 0, -1): i goes 5, 4, 3, 2, 1.
for i in range(5, 0, -1):
print("* " * i)
Demo: Inverted Triangle
for i in range(5, 0, -1):
print(" " + "* " * i)
Part 5: Summary
β
"* " * n prints n copies of "* " (no inner loop needed).
β
Full block: same "* " * 5 for each row (one loop).
β
Triangle: for i in range(1, 6): print('* ' * i).
β
Inverted: for i in range(5, 0, -1): print('* ' * i).
β
Nested loops still work (e.g. condition i >= j for triangle); string multiply is a shortcut in Python.
Congratulations! You now understand how to create Star Patterns with for loops in Python! π
Key Takeaways:
- String multiplication (
"* " * n) is the fastest way for repeated stars - Triangle patterns use
range(1, rows+1)orrange(rows, 0, -1) - Nested loops give full control when you need conditions (i >= j)
- One simple loop +
end=' 'is enough for most patterns
Next Steps:
- Try diamond, pyramid, or hollow patterns
- Add user input (ask how many rows)
- Combine with previous lessons (prime numbers in a pattern)