Python Pyramid Star Pattern Generator
Print aligned, centered pyramid structures using star characters in Python.
How it Works
Pattern printing is a fundamental exercise that trains developers in using loops, variables, and calculating string alignments.
A centered pyramid of height H consists of rows containing spaces and stars. Row `i` (0-indexed) requires `H - i - 1` leading spaces and `2*i + 1` stars.
We use Python's string multiplication capabilities to generate spaces and stars dynamically.
Source Code
Pyramid printing using nested string operations.
pyramid.py
Try in Editordef print_pyramid(height):
for i in range(height):
# Calculate spaces and stars
spaces = " " * (height - i - 1)
stars = "*" * (2 * i + 1)
print(spaces + stars)
print("Pyramid of height 4:")
print_pyramid(4)Terminal Output
Pyramid of height 4:
*
***
*****
*******Real-world Applications
- CLI text formatting design projects
- Foundational syntax learning for students
- Algorithmic character placement logic exercises
Frequently Asked Questions
How can I print an inverted pyramid?
Reverse the iteration: start the loop from `height - 1` and decrement down to `0`.