Print Pascal's Triangle in Python

Print Pascal's triangle up to N rows using a loop and binomial coefficients.

IntermediateLoop ProgramsExample 25 of 25
print-pascal-s-triangle.py
1# Program to print Pascal's triangle
2
3rows = int(input("Enter number of rows: "))
4
5for n in range(rows):
6 # print leading spaces
7 print(" " * (rows - n), end="")
8 coef = 1
9 for k in range(n + 1):
10 print(coef, end=" ")
11 coef = coef * (n - k) // (k + 1)
12 print()

Output

Enter number of rows: 5
    1 
   1 1 
  1 2 1 
 1 3 3 1 
1 4 6 4 1 

What's going on

We compute binomial coefficients iteratively in each row using the relation:

coef = coef * (n - k) // (k + 1).

After this program

If the idea is still fuzzy, read Day 9: Loops and Iteration in the Python course. For a short check, try the Python quiz (300 questions). Stay with all 25 loop programs, or see every topic on Python exercises.