Python Print an Inverted Triangle of Asterisks
We will use Python to write a simple program that prints an inverted triangle of asterisks. This pattern consists of multiple rows of asterisks, with the number of asterisks decreasing in each row.
Example
def
print_inverted_triangle
(
n
)
:
for
i
in
range
(
n
,
0
,
1
)
:
(
'*'
- i
)
Call the function to print a 5-row inverted triangle
print_inverted_triangle
(
5
)
Code analysis:
def print_inverted_triangle(n):defines a class namedprint_inverted_trianglefunction, which takes a parametern, represents the number of rows of the inverted triangle.for i in range(n, 0, -1):UseforThe loop starts fromnand decrements down to 1, each iterationidecreasing by 1.print('*' * i)In each iteration, printiasterisks.'*' * imeans repeating the asteriskitimes.print_inverted_triangle(5)Call the function to print a 5-row inverted triangle.
Output result:
*****
****
***
**
*
Python3 Examples