在Python中,可以使用嵌套循环和字符串格式化功能来输出杨辉三角。以下是一个示例代码:
def generate_pascals_triangle(n):
triangle = []
for i in range(n):
row = [1]
if triangle:
last_row = triangle[-1]
row.extend([sum(pair) for pair in zip(last_row, last_row[1:])])
row.append(1)
triangle.append(row)
return triangle
def print_pascals_triangle(triangle):
n = len(triangle)
max_width = 2 * n - 1
for i, row in enumerate(triangle):
row_str = " ".join(str(num) for num in row)
padding = (max_width - len(row_str)) // 2
print(" " * padding + row_str + " " * padding)
n = int(input("请输入杨辉三角的行数:"))
triangle = generate_pascals_triangle(n)
print_pascals_triangle(triangle)
这段代码首先定义了两个函数:generate_pascals_triangle()
用于生成杨辉三角,print_pascals_triangle()
用于打印杨辉三角。然后,根据用户输入的行数生成杨辉三角并打印出来。