In the previous article we explored the printing of Inverted triangle patterns in Python, now we will look at the implementation of Pyramid pattern in Python. We accept the input value from the user and print a * pattern resembling a pyramid structure which is respective to the number entered by the user in it’s length and number of iterations. If the user enters the number 6 the pattern should appear like:
*
* * *
* * * * *
* * * * * * *
* * * * * * * * *
* * * * * * * * * * *
Working on Pyramid Pattern in Python
This particular example of pattern is a bit different in logic when compared to the previous patterns we have seen so far in the recent articles, this is due to the nature of the pyramid shape. We would not achieve a pyramid pattern without making sure that the resultant output managed to have a balanced equidistant count of * which is also tapering/reducing from bottom point to the start of the pattern.
The program begins by asking for the user input, once it is entered, a looping structure is activated. The initial loop checks for the values from 0 to the entered number, and then the loop containing the j variable checks for the range of the entered number minus i and minus by 1. This part of the loop is important as it makes sure to print the empty space towards the top of the pyramid which is reducing towards the bottom. Finally the k loop makes the program print out the entered range value twice diagonally. By default when reaching the end of the initial loop, the star character is printed out.
n=int(input("Enter n:"))
for i in range(n):
for j in range(n-i-1):
print((" ", end=" ")
for k in range(2*i+1):
print("*", end =" ")
print()
Output:
Enter n:9
*
* * *
* * * * *
* * * * * * *
* * * * * * * * *
* * * * * * * * * * *
* * * * * * * * * * * * *
* * * * * * * * * * * * * * *
* * * * * * * * * * * * * * * * *
Hence, we obtain the required pyramid style pattern. In the next article we will explore the Python program to count the digits.