Print Pascal's Triangle

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

IntermediateTopic: Loop Programs
Back

Python Print Pascal's Triangle Program

This program helps you to learn the fundamental structure and syntax of Python programming.

Try This Code
# Program to print Pascal's triangle

rows = int(input("Enter number of rows: "))

for n in range(rows):
    # print leading spaces
    print(" " * (rows - n), end="")
    coef = 1
    for k in range(n + 1):
        print(coef, end=" ")
        coef = coef * (n - k) // (k + 1)
    print()
Output
Enter number of rows: 5
     1 
    1 1 
   1 2 1 
  1 3 3 1 
 1 4 6 4 1 

Understanding Print Pascal's Triangle

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

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

Note: To write and run Python programs, you need to set up the local environment on your computer. Refer to the complete article Setting up Python Development Environment. If you do not want to set up the local environment on your computer, you can also use online IDE to write and run your Python programs.

Table of Contents