Pattern Programs in Python
In this lesson: Star, pyramid, number and alphabet pattern programs in Python with nested loops — code and output for practice. In Hindi & English.
Why pattern programs
Pattern programs print shapes made of stars or numbers — triangles, pyramids, and so on. They are the classic way to master nested loops (a loop inside a loop). Getting good at them trains you to think in rows and columns, which helps with tables, grids and matrices later.
Star triangle
Python can repeat a string by multiplying, so a simple triangle needs just one loop.
for i in range(1, 6):
print("* " * i)
* *
* * *
* * * *
* * * * *
"* " * i repeats the star i times. As i grows from 1 to 5, each row gets one more star.
Dry run
| i | "* " * i | |
|---|---|---|
| 1 | "* " once | * |
| 2 | "* " twice | * * |
| 3 | "* " three times | * * * |
| 4 | "* " four times | * * * * |
| 5 | "* " five times | * * * * * |
In Python, multiplying a string by a number repeats it — "* " * 3 = "* * * ". As i grows in the loop, each row gets more stars, forming a triangle.
Right-angled with nested loops
To really use nested loops, print each star one at a time.
for i in range(1, 6):
for j in range(i):
print("*", end=" ")
print() # new line after each row
* *
* * *
* * * *
* * * * *
The outer loop (i) is the row; the inner loop (j) prints i stars using end=" " to stay on the line. The empty print() moves to the next row.
Number pattern
for i in range(1, 6):
for j in range(1, i + 1):
print(j, end=" ")
print()
1 2
1 2 3
1 2 3 4
1 2 3 4 5
Same nested-loop structure, but we print the value of j instead of a star, giving a number triangle. Change what the inner loop prints to make different patterns.
Common mistakes
- Forgetting the empty
print(). Without it, all rows run into one line. - Wrong inner range. Row
iusually needsrange(i)orrange(1, i+1)items. - Missing
end=" ". Then each star goes on its own line. - Confusing rows and columns. Outer loop is rows; inner loop is the content of a row.
Summary
- Pattern programs are the best practice for nested loops.
- Outer loop makes rows; inner loop fills each row.
"* " * irepeats a string for quick triangles.- Use
end=" "to stay on a line andprint()for a new row. - Print numbers instead of stars for number patterns.
Next, strengthen loops with Python loops, or try the prime number program.
Frequently Asked Questions
Why are pattern programs important to learn?
How do nested loops make a pattern?
How does Python repeat a character easily?
"* " * 3 gives "* * * ". This lets you print a whole row without an inner loop for simple triangles.What is the difference between print() with and without end?
print() moves to a new line each time. print(x, end="") stays on the same line. In patterns you often print on the same line, then use an empty print() to move to the next row.