Python Program to Print Star Pattern
You can print a star pattern in Python using nested
for loops like this: for i in range(1, n+1): print('*' * i) where n is the number of lines.Examples
Inputn = 3
Output*
**
***
Inputn = 5
Output*
**
***
****
*****
Inputn = 1
Output*
How to Think About It
To print a star pattern, think of each line as having a number of stars equal to the line number. Start from 1 star on the first line, then increase by one star each line until you reach the desired number of lines. Use a loop to repeat this process.
Algorithm
1
Get the number of lines (n) from the user or set it.2
Start a loop from 1 to n (inclusive).3
For each number i in the loop, print i stars on that line.4
Move to the next line and repeat until all lines are printed.Code
python
n = 5 for i in range(1, n + 1): print('*' * i)
Output
*
**
***
****
*****
Dry Run
Let's trace n=3 through the code
1
Set n
n = 3
2
First loop iteration
i = 1, print '*' * 1 -> '*'
3
Second loop iteration
i = 2, print '*' * 2 -> '**'
4
Third loop iteration
i = 3, print '*' * 3 -> '***'
| i | Printed Stars |
|---|---|
| 1 | * |
| 2 | ** |
| 3 | *** |
Why This Works
Step 1: Loop controls lines
The for loop runs from 1 to n, controlling how many lines are printed.
Step 2: Stars printed per line
On each line, '*' * i creates a string with i stars, matching the line number.
Step 3: Print moves to next line
Each print outputs stars and moves to the next line automatically.
Alternative Approaches
Using nested loops
python
n = 5 for i in range(1, n + 1): for j in range(i): print('*', end='') print()
This uses two loops: outer for lines, inner for stars, giving more control but more code.
Using while loop
python
n = 5 i = 1 while i <= n: print('*' * i) i += 1
Uses a while loop instead of for, useful if you prefer while loops.
Complexity: O(n^2) time, O(n) space
Time Complexity
The outer loop runs n times, and each print creates a string of length up to n, so total work is proportional to n^2.
Space Complexity
Each line creates a string of stars up to length n, so space used per line is O(n).
Which Approach is Fastest?
Using string multiplication is faster and simpler than nested loops because it avoids inner loop overhead.
| Approach | Time | Space | Best For |
|---|---|---|---|
| String multiplication | O(n^2) | O(n) | Simple and fast star patterns |
| Nested loops | O(n^2) | O(1) | More control over printing each star |
| While loop | O(n^2) | O(n) | Preference for while loops |
Use string multiplication
'*' * number to quickly create repeated star strings.Beginners often forget that
print() adds a new line automatically, so they try to add extra new lines.