Python Program To Print Pascal’s Triangle (2 Ways)

In this program, we will learn how to print Pascal’s Triangle using the Python programming language.

What is Pascal’s Triangle?

In mathematics, It is a triangular array of the binomial coefficients. It is named after the French mathematician Blaise Pascal.

Pascal's Triangle
In Pascal’s triangle, each number is the sum of the two numbers directly above it.

We will discuss two ways to code it.

  • Using Factorial
  • Without using Factorial

Python Programming Code To Print Pascal’s Triangle

Using Factorial

We have already discussed different ways to find the factorial of a number. So, you look up there to learn more about it.

Code:-

def fact(n):
	res=1
	for c in range(1,n+1):
		res = res*c
	
	return res

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

for i in range(0, rows):
    for j in range(1, rows-i):
        print("  ", end="")

    for k in range(0, i+1):
        coff = int(fact(i)/(fact(k)*fact(i-k)))
        print("  ", coff, end="")
    
    print()

Ouput:-

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

Without using Factorial

Code:-

rows = int(input("Enter the number of rows : "))
for i in range(0, rows):
    coff = 1

    for j in range(1, rows-i):
        print("  ", end="")
    
    for k in range(0, i+1):
        print("  ", coff, end="")
        coff = int(coff * (i - k) / (k + 1))

    print()

Output:-

Enter the number of rows : 8
                 1
               1   1
             1   2   1
           1   3   3   1
         1   4   6   4   1
       1   5   10   10   5   1
     1   6   15   20   15   6   1
   1   7   21   35   35   21   7   1

You can learn about many other Python Programs Here.

Best Books for learning Python with Data Structure, Algorithms, Machine learning and Data Science.

The following two tabs change content below.

Amit Rawat

Founder and Developer at SpiderLabWeb
I love to work on new projects and also work on my ideas. My main field of interest is Web Development.

You may also like...