Editor

Python Program to Print Pascal's Triangle

Intermediate · Patterns

Pascal's triangle is a triangle of numbers where each row starts and ends with 1, and every number inside is the sum of the two numbers just above it. The fifth row is 1 4 6 4 1, the numbers you get when you expand (a + b) to the power 4. This program builds each row from the one before it and prints the rows centred.

Program

pascals_triangle.py
rows = 5 # or: rows = int(input("Enter the number of rows: "))
row = [1] # the top row
for i in range(rows):
# Indent each row so the triangle is centred
print(" " * (rows - i - 1), end="")
for value in row:
print(f"{value:4}", end="") # each number takes 4 columns
print()
# Build the next row: 1, then the sums of neighbouring pairs, then 1
next_row = [1]
for j in range(len(row) - 1):
next_row.append(row[j] + row[j + 1])
next_row.append(1)
row = next_row
Output
           1
         1   1
       1   2   1
     1   3   3   1
   1   4   6   4   1

How it works

  1. row holds the current row as a list, starting with [1] at the top.
  2. Each number is printed with f"{value:4}", which gives it 4 columns, and each row is indented 2 spaces (half of 4) less than the one above, so every number sits between the two numbers over it.
  3. The next row starts with 1, then adds each pair of neighbours, row[j] + row[j + 1], then ends with 1, so [1, 2, 1] becomes [1, 3, 3, 1].
  4. At the end of each pass, row = next_row moves down to the new row.

Other ways to write it

Using math.comb()

Using math.comb()
from math import comb
rows = 5
for n in range(rows):
# The k-th number of row n is "n choose k"
values = [str(comb(n, k)) for k in range(n + 1)]
print(" " * (rows - n - 1) + " ".join(values))
Output
    1
   1 1
  1 2 1
 1 3 3 1
1 4 6 4 1

Every number in Pascal's triangle is a combination, n choose k, so math.comb(n, k) gives it directly; this simpler layout only lines up while every number has one digit, which holds for 5 rows.

The next row with zip()

The next row with zip()
rows = 6
row = [1]
for i in range(rows):
print("Row", i + 1, ":", row)
# Add [0, 1, 2, 1] and [1, 2, 1, 0] place by place to get [1, 3, 3, 1]
row = [a + b for a, b in zip([0] + row, row + [0])]
Output
Row 1 : [1]
Row 2 : [1, 1]
Row 3 : [1, 2, 1]
Row 4 : [1, 3, 3, 1]
Row 5 : [1, 4, 6, 4, 1]
Row 6 : [1, 5, 10, 10, 5, 1]

Adding the row to a copy of itself shifted by one place gives the next row in a single line, and this version prints each row as a list.

Try it yourself

Add a line that prints the sum of each row, and check that the sums are 1, 2, 4, 8 and 16.

Edit the program above and press Run, or open it in the full editor to save it and share it. To watch it run line by line, open it in the visualizer.

All Python programs · CBSE class 12 practical file · Python exercises