Python Print an Isosceles Triangle
We will write a simple Python program to print an isosceles triangle. The triangle is made of asterisks (*); the user enters the height of the triangle and the program prints the isosceles triangle accordingly.
Example
def
print_triangle
(
height
)
:
for
i
in
range
(
height
)
:
Print the leading spaces
(
' '
(
height - i -
1
)
,
end
=
''
)
Print the asterisks
(
'*'
(
2
- i +
1
)
)
The user enters the height of the triangle
height
=
int
(
input
(
"Please enter the height of the triangle: "
)
)
print_triangle
(
height
)
Code analysis:
print_triangle(height)is a function used to print an isosceles triangle.for i in range(height)The loop runs from 0 to height-1, controlling the number of rows printed.print(' ' * (height - i - 1), end='')Print the spaces at the beginning of each row to keep the asterisks centered.print('*' * (2 * i + 1))Print the asterisks for each row; the number of asterisks increases as the row number increases.height = int(input("请输入三角形的高度: "))Get the triangle height entered by the user.print_triangle(height)Call the function to print the triangle.
Output: assuming the user enters a height of 5, the result is as follows:
*
***
*****
*******
*********
Python3 Examples