Pascal’s Triangle in Python

Swati Meher
Python’s Gurus
Published in
2 min readJun 28, 2024

Introduction

Pascal’s Triangle is a fascinating mathematical construct named after the French mathematician Blaise Pascal. It is a triangular array of the binomial coefficients, where each number is the sum of the two directly above it. This simple yet powerful structure has applications in algebra, probability, and combinatorics. In this article, we’ll explore how to generate Pascal’s Triangle using Python and visualize it in a structured format.

Problem Statement

The task is to create a program that generates Pascal’s Triangle for a given number of rows. The triangle should be printed in a centered format to make it visually appealing. Each row of Pascal’s Triangle starts and ends with the number 1, and each number inside the triangle is the sum of the two numbers directly above it from the previous row.

Approach

To solve this problem, we can follow these steps:

1. Read the number of rows from the user.
2. Initialize an empty list to store the rows of Pascal’s Triangle.
3. Use a loop to construct each row:
- Start each row with a list of 1's.
- For each element in the row (except the first and last), calculate the value as the sum of the two elements directly above it from the previous row.
4. Append each row to the triangle.
5. Print the triangle in a centered format.

Code Implementation

Here’s the Python code to generate Pascal’s Triangle and print it:

no_of_rows = eval(input("Enter the number of rows: "))
triangle = []
for i in range(no_of_rows):
trow = [1] * (i + 1)
for j in range(1, i):
trow[j] = triangle[i - 1][j - 1] + triangle[i - 1][j]
triangle.append(trow)
for trow in triangle:
print(" ".join(map(str, trow)).center(no_of_rows * 2))

Demo

Let’s walk through an example. Suppose the user inputs `5` as the number of rows. The program will generate the following Pascal’s Triangle:

        1 
1 1
1 2 1
1 3 3 1
1 4 6 4 1

Each row starts and ends with 1. The numbers in between are sums of the pairs of numbers directly above them. For instance, in the third row, the number 2 is the sum of the two 1’s above it.

Conclusion

Pascal’s Triangle is a classic example of a simple yet powerful algorithm that can be implemented with basic programming constructs. The approach we discussed demonstrates how nested loops and list operations can be used to build such a structure. This exercise not only helps in understanding the properties of Pascal’s Triangle but also provides a practical application of control flow and list manipulations in Python.

Happy Coding ;)

--

--

Swati Meher
Python’s Gurus

Data Analyst | Gadget Lover | Hoping to reach 300 Followers here.