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.
def 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)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`.
More Examples
Recommended Python Resources
Expand your knowledge with related interactive tutorials, cheat sheets, and code comparisons.
Python Loops
Learn how to use Python loops to iterate over data. Master for loops, while loops, break, continue, and loop best practices with interactive examples.
How to Sort a List in Python
Learn how to sort a list in Python using the sort() method and the sorted() function. Discover custom key sorting and reverse order examples.
Python Regex Patterns (re module)
Reference guide for Python regular expressions. Learn match, search, findall, sub, and essential regex patterns.
Python Decorators vs Decorator Design Pattern: The Key Differences
Compare Python decorators and the classic decorator design pattern. Understand the differences between definition-time function wrapping and runtime dynamic object composition with runnable code.