Python Print Equilateral Triangle Pattern

Document 对象参考手册Python3 Examples

We will use Python to write a simple program to print an equilateral triangle pattern. This pattern consists of asterisks (*), with the number of asterisks in each row gradually increasing, forming an equilateral triangle.

Example

def print_triangle(n):
    for i in range(n):
        print(' ' * (n - i - 1) + '*' * (2 * i + 1))

# Call the function to print an equilateral triangle with height 5
print_triangle(5)

Code Analysis:

  1. print_triangle(n)is a function that takes a parametern, which represents the height of the triangle.
  2. for i in range(n)is a loop, from 0 ton-1iterate, controlling the number of printed rows.
  3. ' ' * (n - i - 1)is used to print spaces at the beginning of each row, so that the asterisks can be displayed centered. As the number of rows increases, the number of spaces gradually decreases.
  4. '*' * (2 * i + 1)is used to print asterisks, the number of asterisks in each row is2 * i + 1, as the number of rows increases, the number of asterisks gradually increases.
  5. print(' ' * (n - i - 1) + '*' * (2 * i + 1))Combine the spaces and asterisks together to print the content of each row.

Output result:

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

Document 对象参考手册Python3 Examples

Other Extensions