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

Python Print an Upright Triangle Pattern

Python Print an Upright Triangle Pattern

Document Object Reference Manual Python3 Examples

We will write a simple Python program to print an upright triangle pattern. The pattern is made of asterisks (*), and the number of asterisks increases on each row, forming an upright triangle.

Example

def

print_triangle

(

n

)

:

   

for

i

in

range

(

n

)

:

       

print

(

' '

(

n - i -

1

)

'*'

(

2

1

)

)

Call the function to print an upright triangle of height 5

print_triangle

(

5

)

Code analysis:

  1. print_triangle(n) is a function that takes one parameter n, representing the height of the triangle.
  2. for i in range(n) is a loop from 0 to n-1 , controlling the number of rows printed.
  3. ' ' * (n - i - 1) Used to print spaces at the beginning of each row so that the asterisks are centered. As the row number increases, the number of spaces gradually decreases.
  4. '*' * (2 * i + 1) Used to print the asterisks; the number of asterisks on each row is 2 * i + 1, and increases as the row number increases.
  5. print(' ' * (n - i - 1) + '*' * (2 * i + 1)) Combine the spaces and asterisks and print the content of each row.

Output result:

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

Document Object Reference Manual Python3 Examples