Issue
Let's say the user inputs an integer h where h >= 0.
SAMPLE INPUT:
1
SAMPLE OUTPUT:
*
SAMPLE INPUT:
3
SAMPLE OUTPUT:
*
***
*****
This is my code. However, I can't seem to properly align the asterisks to make a proper triangle.
n = int(input())
def triangle(n):
a = n
b = 0
c = 1
for i in range(0, n):
for j in range(0, a):
print(end=" ")
a = a - 1
for k in range (0, i):
print("*"*(c+b), end=" ")
print("\r")
b = b + 1
c = c + 1
print(triangle(n))
Solution
Here is a slightly different approach where you utilize the fact that for each row, the number of stars will be, 2 * row - 1
:
def print_triangle(height: int) -> None:
base = 2 * height - 1
for row in range(1, height + 1):
num_stars = 2 * row - 1
num_left_spaces = (base - num_stars) // 2
for _ in range(num_left_spaces):
print(" ", end="")
for _ in range(num_stars):
print("*", end="")
print()
def get_int_input(prompt: str) -> int:
while True:
try:
return int(input(prompt))
except ValueError:
print("Error: Enter an integer, try again...")
n = get_int_input("Enter the height of the triangle: ")
print_triangle(n)
Example Usage 1:
Enter the height of the triangle: 1
*
Example Usage 2:
Enter the height of the triangle: 3
*
***
*****
Example Usage 3:
Enter the height of the triangle: 5
*
***
*****
*******
*********
Answered By - Sash Sinha
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.