Python Print an Upright Triangle Pattern
We will write a simple Python program to print an upright triangle pattern. The pattern is made of asterisks (*), and the number of asterisks increases on each row, forming an upright triangle.
Example
def
print_triangle
(
n
)
:
for
i
in
range
(
n
)
:
(
' '
(
n - i -
1
)
'*'
(
2
- i +
1
)
)
Call the function to print an upright triangle of height 5
print_triangle
(
5
)
Code analysis:
print_triangle(n)is a function that takes one parametern, representing the height of the triangle.for i in range(n)is a loop from 0 ton-1, controlling the number of rows printed.' ' * (n - i - 1)Used to print spaces at the beginning of each row so that the asterisks are centered. As the row number increases, the number of spaces gradually decreases.'*' * (2 * i + 1)Used to print the asterisks; the number of asterisks on each row is2 * i + 1, and increases as the row number increases.print(' ' * (n - i - 1) + '*' * (2 * i + 1))Combine the spaces and asterisks and print the content of each row.
Output result:
*
***
*****
*******
*********
Python3 Examples