编写一个 Python 程序,使用 for 循环打印杨辉三角数字模式。要打印杨辉三角,我们必须使用嵌套的 for 循环来迭代多层数字并计算每次迭代中每个数字的阶乘。
在此示例中,我们使用内置的 math factorial 函数。请参考 For loop 和 while loop 来理解迭代。
from math import factorial
rows = int(input("Enter Pascals Triangle Number Pattern Rows = "))
print("====Pascals Triangle Number Pattern====")
for i in range(0, rows):
for j in range(rows - i + 1):
print(end = ' ')
for k in range(0, i + 1):
print(factorial(i)//(factorial(k) * factorial(i - k)), end = ' ')
print()

这个 示例 程序使用 while 循环打印数字杨辉三角。
# using while loop
from math import factorial
rows = int(input("Enter Rows = "))
print("====Pattern====")
i = 0
while(i < rows):
j = 0
while(j <= rows - i):
print(end = ' ')
j = j + 1
k = 0
while(k <= i):
print(factorial(i)//(factorial(k) * factorial(i - k)), end = ' ')
k = k + 1
print()
i = i + 1
