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

Python Print an Inverted Triangle of Asterisks

Python Print an Inverted Triangle of Asterisks

Document Object Reference Manual Python3 Examples

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

)

:

       

print

(

'*'

)

Call the function to print a 5-row inverted triangle

print_inverted_triangle

(

5

)

Code analysis:

  1. def print_inverted_triangle(n): defines a class named print_inverted_triangle function, which takes a parameter n, represents the number of rows of the inverted triangle.
  2. for i in range(n, 0, -1): Use for The loop starts from n and decrements down to 1, each iteration i decreasing by 1.
  3. print('*' * i) In each iteration, print i asterisks.'*' * i means repeating the asterisk i times.
  4. print_inverted_triangle(5) Call the function to print a 5-row inverted triangle.

Output result:

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

Document Object Reference Manual Python3 Examples