要用Python打印楊輝三角,可以按照以下步驟編寫代碼:
def print_pascal_triangle(n):
for i in range(n):
coef = 1
for j in range(1, n - i + 1):
print(" ", end="")
for j in range(0, i + 1):
if j > 0:
coef = coef * (i - j + 1) // j
print(" ", coef, end="")
print()
n = int(input("請輸入要打印的行數:"))
print_pascal_triangle(n)
運行以上代碼,輸入要打印的行數,即可在控制臺打印出相應行數的楊輝三角。