A Pattern code or Pyramid Patterns are made using the combination of stars or numbers and represent a specific pattern. We usually code these with the help of loops to build better logic. In this article we are going learn to print a Left Half Pyramid also called an Increasing Star Pattern. The left half pyramid is one of the two basal patterns codes to be able create complexer pattern codes. This is what a left half pyramid looks like:
To build a left half pyramid let us first create a for loop to print a
'n=5' number of times.
for i in range(5): print('*')
* * * * *
for loop above prints 5 stars in each row. Now, let us print these in the same row. We can do that with an additional argument
for i in range(5): print('*', end='')
Now that we have printed these stars in the same row, we will use another
for loop outside this
for loop to print 5 of such rows to create a square.
for i in range(5): for j in range(5): print('*', end='') print()
***** ***** ***** ***** *****
Now, carefully observe that the outer for loop is responsible to print the number of rows or the number of times our nested for loop is running. Whereas, the nested loop is responsible to print the number of stars in a particular row. Hence, to compare this square to what we want for our final result we will make changes in our nested for loop.
We want our nested loop to run until the value of
j becomes one more than the value of our outer iterable
i. For eg: In the first row,
i=0, the outer loop runs once, and the inner loop will run until the value if j becomes 1 where it terminates.
Now, to achieve this, we simply need to set the range of our inner loop to one more than the value of our outer loop's iterable, i.e
for i in range(5): for j in range(i+1): print('*', end='') print()
* ** *** **** *****
This gives us a simple increasing star pattern or a Left Half Pyramid.
This pyramid can now be used to create other star patterns like Right-Half Pyramid, Whole Pyramid/Hill Pattern, Diamond Pattern etc... Check the series https://youtube.com/playlist?list=PLyMom0n-MBrpVcMqVV9kbA-hq2ygir0uW to learn to use this increasing star pattern to create complexer pattern codes.