1. Introduction
Patterns play a fundamental role in programming. They help improve logic-building and are often used in beginner exercises to strengthen coding basics. One of the most popular patterns in programming is the pyramid of stars.
In this blog post, we will learn how to write a Python program to print a pattern of stars (like a pyramid).
2. Program Overview
1. Get the number of rows for the pyramid from the user.
2. Loop through each row to print spaces and stars.
3. Display the pyramid.
3. Code Program
# Python program to print a pyramid pattern of stars
# Get the number of rows for the pyramid
rows = int(input("Enter the number of rows for the pyramid: "))
# Loop to print each row
for i in range(1, rows + 1):
# Print spaces
for j in range(1, rows - i + 1):
print(" ", end="")
# Print stars
for k in range(1, 2 * i):
print("*", end="")
# Move to the next line after completing the current row
print()
Output:
For rows = 4: * *** ***** *******
4. Step By Step Explanation
1. First, we request the user to input the number of rows for the pyramid. This determines the height of our pyramid.
2. We then initiate a for loop to iterate through each row. The outer loop runs rows times, which is the number of rows in our pyramid.
3. Within this loop, we have another loop to print spaces. The number of spaces decreases as we move down the pyramid. This is why we print rows - i + 1 spaces in each row.
4. Another loop follows this to print the stars. The number of stars increases by 2 for each subsequent row. Hence, we print 2 * i - 1 stars in each row.
5. After printing the spaces and stars for a row, we move to the next line using print().
6. This process continues until the pyramid is fully printed.
Comments
Post a Comment
Leave Comment