Python Output an Isosceles Triangle

Document 对象参考手册Python3 Examples

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)

Code explanation:

  1. print_triangle(height)This is a function used to print an isosceles triangle.
  2. for i in range(height)The loop goes from 0 to height-1, controlling the number of rows printed.
  3. print(' ' * (height - i - 1), end='')Print the spaces before each line to ensure the asterisks are centered.
  4. print('*' * (2 * i + 1))Print the asterisks for each line; the number of asterisks increases as the row number increases.
  5. height = int(input("请输入三角形的高度: "))Get the height of the triangle input by the user.
  6. 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:

    *
   ***
  *****
 *******
*********

Document 对象参考手册Python3 Examples

Other extensions