在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()
用于打印楊輝三角。然后,根據用戶輸入的行數生成楊輝三角并打印出來。