Python Program to Print Pyramid Star Pattern
for i in range(1, n+1): print(' '*(n-i) + '*'*(2*i-1)) where n is the number of pyramid rows.Examples
How to Think About It
Algorithm
Code
n = int(input('Enter number of rows: ')) for i in range(1, n + 1): print(' ' * (n - i) + '*' * (2 * i - 1))
Dry Run
Let's trace the program for input n=3 to see how it prints the pyramid.
Input
User enters n = 3
First row (i=1)
Print spaces: 3 - 1 = 2 spaces, Print stars: 2*1 - 1 = 1 star Output: ' *'
Second row (i=2)
Print spaces: 3 - 2 = 1 space, Print stars: 2*2 - 1 = 3 stars Output: ' ***'
Third row (i=3)
Print spaces: 3 - 3 = 0 spaces, Print stars: 2*3 - 1 = 5 stars Output: '*****'
| Row (i) | Spaces | Stars | Printed Line |
|---|---|---|---|
| 1 | 2 | 1 | * |
| 2 | 1 | 3 | *** |
| 3 | 0 | 5 | ***** |
Why This Works
Step 1: Spaces decrease each row
We print spaces first to push stars to the right, using n - i spaces for the current row.
Step 2: Stars increase by two
Stars form the pyramid shape by increasing count as 2 * i - 1, making odd numbers like 1, 3, 5.
Step 3: Loop controls rows
The outer loop runs from 1 to n, printing one row of the pyramid each time.
Alternative Approaches
n = int(input('Enter number of rows: ')) for i in range(1, n + 1): stars = '*' * (2 * i - 1) print(stars.center(2 * n - 1))
n = int(input('Enter number of rows: ')) i = 1 while i <= n: print(' ' * (n - i) + '*' * (2 * i - 1)) i += 1
Complexity: O(n^2) time, O(1) space
Time Complexity
The program runs a loop for each row and prints up to 2*n-1 characters, so time grows roughly with n squared.
Space Complexity
Only a few variables are used; no extra data structures, so space is constant.
Which Approach is Fastest?
Both for-loop and while-loop methods have similar speed; using string center is cleaner but similar in performance.
| Approach | Time | Space | Best For |
|---|---|---|---|
| For loop with spaces and stars | O(n^2) | O(1) | Clear control over spaces and stars |
| String center method | O(n^2) | O(1) | Cleaner code, easier alignment |
| While loop method | O(n^2) | O(1) | Alternative loop style, less common |