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
Run in browser1# Program to print Pascal's triangle23rows = int(input("Enter number of rows: "))45for n in range(rows):6 # print leading spaces7 print(" " * (rows - n), end="")8 coef = 19 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).