Python Print Inverted Triangle

Document 对象参考手册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 in each row. As the number of rows increases, the number of asterisks in each row 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: Defines the height of the inverted triangle as 5 rows.
  2. for i in range(n, 0, -1): The outer loop starts fromn, decreasing by 1 each iteration, until it reaches 1. This loop controls the number of rows.
  3. for j in range(i): The inner loop starts from 0 and ends ati-1. This loop controls the number of asterisks printed in each row.
  4. print("*", end=" "): Print an asterisk and stay on the same line.
  5. print(): After each row ends, print a blank line so that the asterisks of the next row start on a new line.

Output Result:

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

Document 对象参考手册Python3 Examples

Other Extensions