Python Program to create Pyramid Pattern

Write a Python program to generate pyramid patterns based on the number of rows provided by the user. Pyramid patterns are often used in programming to practice loops and logic building.

Input-Output Examples

plaintext
Example 1:
Input: Enter the number of rows: 5
Output:
    *  
   ***  
  *****  
 *******  
*********

Example 2:
Input: Enter the number of rows: 3
Output:
  *  
 ***  
*****

Algorithm to print the Pyramid Pattern

  1. Start
  2. Take input: Prompt the user to enter the number of rows for the pyramid pattern.
  3. Loop through the number of rows:
    • For each row, print a combination of spaces and asterisks (*).
    • The number of spaces decreases, and the number of asterisks increases as you move to the next row.
  4. Display the pattern: Print the pyramid pattern after constructing it row by row.
  5. End

Python Program to print the Pyramid Pattern

python
# Python program to create pyramid pattern

# Take input from the user for the number of rows
rows = int(input("Enter the number of rows: "))

# Loop to create the pyramid pattern
for i in range(1, rows + 1):
    # Print leading spaces
    print(" " * (rows - i), end="")
    # Print stars for the pyramid
    print("*" * (2 * i - 1))

Code Explanation

  1. Taking input from the user:
    The program prompts the user to input the number of rows for the pyramid. This is taken using input() and converted to an integer using int().
  2. Creating the pyramid pattern:
    The program uses a for loop to iterate through the number of rows. For each row:
    • The number of spaces printed decreases as the row number increases, achieved using " " * (rows - i).
    • The number of asterisks (*) printed increases by 2 for each row, starting from 1 in the first row, which is controlled by "*" * (2 * i - 1).
  3. Displaying the output:
    The print() function is used to display each row of the pyramid. The pattern is printed row by row, with the correct combination of spaces and asterisks for each row.

Python

2397

196

Related Articles