PythonMastery

Pascal's triangle in Python

Print Pascal's triangle by building each row from the one above it, then a centred version that uses math.comb() for each value.

In Pascal's triangle, each row starts and ends with 1, and every other number is the sum of the two numbers above it. Row 4 (counting the top row as row 0) is 1 4 6 4 1, because 1 + 3 = 4, 3 + 3 = 6 and 3 + 1 = 4.

The program

python
rows = int(input("Number of rows: "))

row = [1]
for _ in range(rows):
    print(" ".join(str(n) for n in row))
    middle = [row[j] + row[j + 1] for j in range(len(row) - 1)]
    row = [1] + middle + [1]

Typed in this example: 6. Press Run to type your own.

output
Number of rows: 6
1
1 1
1 2 1
1 3 3 1
1 4 6 4 1
1 5 10 10 5 1

How it works

A centred triangle with math.comb()

The number in row i, position k (both counted from 0) is the number of ways to choose k items from i. math.comb(i, k) calculates it directly, so each value can be found without the row above it:

python
import math

rows = 5

lines = []
for i in range(rows):
    lines.append(" ".join(str(math.comb(i, k)) for k in range(i + 1)))

width = len(lines[-1])
for line in lines:
    print(line.center(width).rstrip())
output
    1
   1 1
  1 2 1
 1 3 3 1
1 4 6 4 1

Learn the idea: Loops: for, while, and the Pythonic Patterns, Lists & Sequences