Private archive copy · Unofficial site · Content copyright belongs to Runoob Tutorial and the original authors · View Original

Python Print an Inverted Triangle

Python Print an Inverted Triangle

Document Object Reference Manual Python3 Examples

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

)

:

       

print

(

"*"

,

end

=

" "

)

   

print

(

)

Code analysis:

  1. n = 5: Define the height of the inverted triangle as 5 rows.
  2. for i in range(n, 0, -1): The outer loop starts at n and decreases by 1 each time down to 1. This loop controls the number of rows.
  3. for j in range(i): The inner loop starts at 0 and runs to i-1 . This loop controls the number of asterisks printed on each row.
  4. print("*", end=" "): Print one asterisk and stay on the same line.
  5. 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:

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

Document Object Reference Manual Python3 Examples