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
- Start
- Take input: Prompt the user to enter the number of rows for the pyramid pattern.
- 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.
- For each row, print a combination of spaces and asterisks (
- Display the pattern: Print the pyramid pattern after constructing it row by row.
- 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
- Taking input from the user:
The program prompts the user to input the number of rows for the pyramid. This is taken usinginput()
and converted to an integer usingint()
. - Creating the pyramid pattern:
The program uses afor
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)
.
- The number of spaces printed decreases as the row number increases, achieved using
- Displaying the output:
Theprint()
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.