用python编写函数,接收一个整数n作为参数,打印杨辉三角前n行
时间: 2024-05-31 12:08:38 浏览: 94
使用python打印十行杨辉三角过程详解
def print_yanghui(n):
# 初始化杨辉三角列表
yanghui = [[1], [1, 1]]
# 打印前两行杨辉三角
for i in range(2):
print(" " * (n - i - 1), end="")
for j in range(i + 1):
print(yanghui[i][j], end=" ")
print()
# 打印后面的杨辉三角
for i in range(2, n):
row = [1]
for j in range(1, i):
row.append(yanghui[i-1][j-1] + yanghui[i-1][j])
row.append(1)
yanghui.append(row)
print(" " * (n - i - 1), end="")
for num in row:
print(num, end=" ")
print()
# 测试函数
print_yanghui(5)
阅读全文