How to print a triangle in Python?

In Python, you can use loops to print out a triangle. Here is a common method:

# 定义三角形的行数
rows = 5

# 外层循环控制行数
for i in range(1, rows + 1):
    # 内层循环控制每行的输出
    for j in range(1, i + 1):
        print("*", end=" ")  # 使用end参数设置输出结束符为一个空格
    print()  # 输出完一行后换行显示

Running the above code will produce a triangle made of asterisks.

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

The number of rows can be adjusted as needed to output triangles with different row numbers.

bannerAds