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

Python Print an Isosceles Triangle

Python Print an Isosceles Triangle

Document Object Reference Manual Python3 Examples

We will write a simple Python program to print an isosceles triangle. The triangle is made of asterisks (*); the user enters the height of the triangle and the program prints the isosceles triangle accordingly.

Example

def

print_triangle

(

height

)

:

   

for

i

in

range

(

height

)

:

       

Print the leading spaces

       

print

(

' '

(

height - i -

1

)

,

end

=

''

)

       

Print the asterisks

       

print

(

'*'

(

2

1

)

)

The user enters the height of the triangle

height

=

int

(

input

(

"Please enter the height of the triangle: "

)

)

print_triangle

(

height

)

Code analysis:

  1. print_triangle(height) is a function used to print an isosceles triangle.
  2. for i in range(height) The loop runs from 0 to height-1, controlling the number of rows printed.
  3. print(' ' * (height - i - 1), end='') Print the spaces at the beginning of each row to keep the asterisks centered.
  4. print('*' * (2 * i + 1)) Print the asterisks for each row; the number of asterisks increases as the row number increases.
  5. height = int(input("请输入三角形的高度: ")) Get the triangle height entered by the user.
  6. print_triangle(height) Call the function to print the triangle.

Output: assuming the user enters a height of 5, the result is as follows:

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

Document Object Reference Manual Python3 Examples