Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
13 changes: 13 additions & 0 deletions Pyramid of stars
Original file line number Diff line number Diff line change
@@ -0,0 +1,13 @@
# Program to create a pyramid of stars

rows = int(input("Enter the number of rows: "))

for i in range(1, rows + 1):
for spaces in range(1, rows - i + 1):
print(end=' ')

for stars in range(1, i + 1):
print('*', end=' ')

print()

31 changes: 31 additions & 0 deletions pyramid_of_stars.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,31 @@
# Program to print a centered full pyramid of stars based on user input

def get_positive_int(prompt: str) -> int:
"""Prompt the user until they provide a positive integer (> 0)."""
while True:
try:
value = int(input(prompt).strip())
if value <= 0:
print("Please enter a positive integer greater than zero.")
continue
return value
except ValueError:
print("Invalid input. Please enter a valid integer.")
Comment on lines +5 to +13
Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

suggestion: Consider handling KeyboardInterrupt to allow graceful exit.

Currently, pressing Ctrl+C results in an unhandled exception. Catching KeyboardInterrupt would allow the program to exit cleanly.



def draw_pyramid(rows: int) -> None:
"""Print a centered full pyramid of stars with the given number of rows."""
for i in range(1, rows + 1):
spaces = ' ' * (rows - i)
stars = '* ' * i
# rstrip to avoid trailing space at line end
print(f"{spaces}{stars.rstrip()}")


def main() -> None:
rows = get_positive_int("Enter the number of rows: ")
draw_pyramid(rows)


if __name__ == "__main__":
main()