Pyramid Star Pattern

 Pyramid Star Pattern Using Python

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.

  1. Take height from user input.
  2. Now we run nested for loops
  3. Initialize x=0
  4. First for loop:  repeat steps from 5 to 9 till x is less than height.
  5. Initialize y=0
  6. First inner for loop: Repeat steps 7 till y is less than height-x.
  7. print three spaces
  8. break first inner for loop
  9. Initialize y=0
  10. Second inner for loop: Repeat steps 11 till y is less than 2x+1.
  11. print space star(*) space
  12. break second inner for loop 
  13. print next line
  14. 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

Pyramid Star Pattern

If you have any queries regarding this code, comment on your problem below. 

Leave A Comment

Your email address will not be published. Required fields are marked *