Print Pyramid Pattern
Center a solid star pyramid with Python loops. Students calculate leading spaces and odd star counts, then trace the separate newline that completes each row.
1# Take n2n = int(input("Enter number of rows: "))34# Print pyramid5for i in range(1, n + 1):6 # Print spaces7 for j in range(n - i):8 print(" ", end="")9 # Print stars10 for j in range(2 * i - 1):11 print("*", end="")12 print()
Output
Enter number of rows: 5
*
***
*****
*******
*********In this one
- Compute indentation
- Use odd star counts
- Center rows with two loops
How it works
- 1
Print n - i leading spaces.
- 2
Print 2 * i - 1 stars.
- 3
End the row and advance i.
Edge cases
What happens for n = 1?
What happens for n = 1?
There are no leading spaces and one star.
What happens for n = 0?
What happens for n = 0?
No rows print.
What's going on
Row i starts with n - i spaces and then contains 2 * i - 1 stars. As the row grows, indentation shrinks.
For n equal to three, the rows have two, one, zero leading spaces and one, three, five stars. Both inner loops suppress newlines; the final empty print ends the row. Alignment is easiest to inspect in a fixed-width font.
What happens for n = 1? There are no leading spaces and one star.
What happens for n = 0? No rows print.
Quiz
Tap an option. The answer stays hidden until you pick.
Question 1
Why are star counts odd?
Pick an answer to check it.
Question 2
What happens for n = 1?
Pick an answer to check it.
Questions people ask
What happens for n = 1?
There are no leading spaces and one star.
What happens for n = 0?
No rows print.
Why are star counts odd?
The formula is 2 * i - 1.
๐Related Content
- ๐
Phase 2 - Learn Concepts
Review Phase 2 concepts and explanations
- ๐
Phase 2 - Quiz
Test your Phase 2 understanding with quiz questions
- ๐ป
Phase 2 - All Practice Problems
Explore all practice problems for Phase 2
- ๐
Master Your Logic Building - Complete Course
Browse all phases and tutorials
- ๐ง
Logic Building Overview
Learn about the complete logic building curriculum