In this post, we will learn how to print a Pyramid Star Pattern Using Python with the help of python. This is a post under the category Build Concepts in Coding
Approach
Our approach will be simple. We will run two for loops. The first for loop will help us to move from top to bottom and the second for loop will help us to move from left to right. So with the help of these two loops.
Here we will use two inner for loops inside one main for loop. The first inner for loop is used to print spaces required before printing the star. The second inner for loop is used to print the star.
Algorithm For Pyramid Star Pattern Using Python
Here is the step-by-step algorithm for better understanding.
- Take height from user input.
- Now we run nested for loops
- Initialize x=0
- First for loop: repeat steps from 5 to 9 till x is less than height.
- Initialize y=0
- First inner for loop: Repeat steps 7 till y is less than height-x.
- print three spaces
- break first inner for loop
- Initialize y=0
- Second inner for loop: Repeat steps 11 till y is less than 2x+1.
- print space star(*) space
- break second inner for loop
- print next line
- break outer for loop
Python Code To Print Right Angled Triangle Star Pattern
#function to print pattern
def drawPyramid(height):
#first for loop from go to top to bottom
for x in range(0, height):
#these inner for loop to move left to right
#This for loop will used to print spaces required before star
for y in range(0, int(height-x)):
print(' ', end='')
# This for loop will print star
for y in range(0, 2*x+1):
print(' * ', end='')
print('')
height = int(input("Enter the height of triangle "))
drawPyramid(height )
Code Explanation
Explanation for first inner loop
for y in range(0, int(height-x)):
print(‘ ‘, end=”)
In this, for loop, we will print three spaces. The condition used here is in the range of 0 to height -x.
For Example
Let
height = 4 and x = 0
so here loop will run for height-x i.e> 4-0= 4 times. Here it prints spaces and the pointer is in the center to print the star in the next for loop.
Output of the following code will be
If you have any queries regarding this code, comment on your problem below.