How can Python output a triangle?
Python offers various ways to output a triangle. Here are two commonly used methods:
Option 1: Utilize nested loops.
n = 5 # 三角形的行数
for i in range(n):
for j in range(i + 1):
print("*", end="")
print()
Output result:
*
**
***
****
*****
Option 2: Implementing string multiplication.
n = 5 # 三角形的行数
for i in range(n):
print("*" * (i + 1))
Output of the result:
*
**
***
****
*****
You can change the size of the triangle by adjusting the value of variable n.