Python Output an Isosceles Triangle
We will use Python to write a simple program to output an isosceles triangle. This triangle will be composed of asterisks (*). The user will input the height of the triangle, and the program will output the corresponding isosceles triangle based on the height.
Example
def print_triangle(height):
for i in range(height):
# Print the leading spaces
print(' ' * (height - i - 1), end='')
# Print asterisks
print('*' * (2 * i + 1))
# User inputs the height of the triangle
height = int(input("Please enter the height of the triangle: "))
print_triangle(height)
for i in range(height):
# Print the leading spaces
print(' ' * (height - i - 1), end='')
# Print asterisks
print('*' * (2 * i + 1))
# User inputs the height of the triangle
height = int(input("Please enter the height of the triangle: "))
print_triangle(height)
Code explanation:
print_triangle(height)This is a function used to print an isosceles triangle.for i in range(height)The loop goes from 0 to height-1, controlling the number of rows printed.print(' ' * (height - i - 1), end='')Print the spaces before each line to ensure the asterisks are centered.print('*' * (2 * i + 1))Print the asterisks for each line; the number of asterisks increases as the row number increases.height = int(input("请输入三角形的高度: "))Get the height of the triangle input by the user.print_triangle(height)Call the function to print the triangle.
Output result: Assuming the user enters a height of 5, the output is as follows:
* *** ***** ******* *********Other extensions
Python3 Examples