Python Print an Inverted Triangle
In Python, we can use nested loops to print an inverted triangle. The outer loop controls the number of rows, and the inner loop controls the number of asterisks printed on each row. As the row number increases, the number of asterisks gradually decreases.
Example
n
=
5
Define the height of the inverted triangle
for
i
in
range
(
n
,
0
,
1
)
:
for
j
in
range
(
i
)
:
(
"*"
,
end
=
" "
)
(
)
Code analysis:
n = 5: Define the height of the inverted triangle as 5 rows.for i in range(n, 0, -1): The outer loop starts atnand decreases by 1 each time down to 1. This loop controls the number of rows.for j in range(i): The inner loop starts at 0 and runs toi-1. This loop controls the number of asterisks printed on each row.print("*", end=" "): Print one asterisk and stay on the same line.print(): Print a blank line at the end of each row so that the next row's asterisks start on a new line.
Output result:
* * * * *
* * * *
* * *
* *
*
Python3 Examples