Python Program to Print Pyramid Pattern
for i in range(1, n+1): print(' '*(n-i) + '*'*(2*i-1)) where n is the number of pyramid levels.Examples
How to Think About It
Algorithm
Code
n = int(input('Enter number of levels: ')) for i in range(1, n + 1): print(' ' * (n - i) + '*' * (2 * i - 1))
Dry Run
Let's trace the pyramid pattern for n=3 through the code
Input
n = 3
First line (i=1)
spaces = 3 - 1 = 2, stars = 2*1 - 1 = 1, print ' *'
Second line (i=2)
spaces = 3 - 2 = 1, stars = 2*2 - 1 = 3, print ' ***'
Third line (i=3)
spaces = 3 - 3 = 0, stars = 2*3 - 1 = 5, print '*****'
| i | spaces | stars | line output |
|---|---|---|---|
| 1 | 2 | 1 | * |
| 2 | 1 | 3 | *** |
| 3 | 0 | 5 | ***** |
Why This Works
Step 1: Spaces decrease each line
We print n - i spaces to push stars to the right, creating the pyramid shape.
Step 2: Stars increase by two
We print 2 * i - 1 stars to form the pyramid's width, growing by two each line.
Step 3: Loop controls lines
The outer loop runs from 1 to n, controlling how many lines the pyramid has.
Alternative Approaches
n = int(input('Enter levels: ')) i = 1 while i <= n: print(' ' * (n - i) + '*' * (2 * i - 1)) i += 1
n = int(input('Enter levels: ')) for i in range(1, n + 1): print(('*' * (2 * i - 1)).center(2 * n - 1))
Complexity: O(n^2) time, O(1) space
Time Complexity
The program uses nested printing for each line, with the number of stars and spaces growing linearly, resulting in O(n^2) time.
Space Complexity
Only a few variables are used, and printing is done directly, so space complexity is O(1).
Which Approach is Fastest?
All approaches have similar time complexity; using string center method improves readability but not speed.
| Approach | Time | Space | Best For |
|---|---|---|---|
| For loops with manual spaces | O(n^2) | O(1) | Clear control over spaces and stars |
| While loops | O(n^2) | O(1) | Beginners learning loop basics |
| String center method | O(n^2) | O(1) | Cleaner code and readability |