Python Print Equilateral Triangle Pattern
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)
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:
print_triangle(n)is a function that takes a parametern, which represents the height of the triangle.for i in range(n)is a loop, from 0 ton-1iterate, controlling the number of printed rows.' ' * (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.'*' * (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.print(' ' * (n - i - 1) + '*' * (2 * i + 1))Combine the spaces and asterisks together to print the content of each row.
Output result:
* *** ***** ******* *********Other Extensions
Python3 Examples