Python Program to Print Pascal's Triangle
Intermediate · Patterns
Pascal's triangle is a triangle of numbers where each row starts and ends with 1, and every number inside is the sum of the two numbers just above it. The fifth row is 1 4 6 4 1, the numbers you get when you expand (a + b) to the power 4. This program builds each row from the one before it and prints the rows centred.
Program
1
1 1
1 2 1
1 3 3 1
1 4 6 4 1How it works
rowholds the current row as a list, starting with[1]at the top.- Each number is printed with
f"{value:4}", which gives it 4 columns, and each row is indented 2 spaces (half of 4) less than the one above, so every number sits between the two numbers over it. - The next row starts with 1, then adds each pair of neighbours,
row[j] + row[j + 1], then ends with 1, so[1, 2, 1]becomes[1, 3, 3, 1]. - At the end of each pass,
row = next_rowmoves down to the new row.
Other ways to write it
Using math.comb()
1 1 1 1 2 1 1 3 3 1 1 4 6 4 1
Every number in Pascal's triangle is a combination, n choose k, so math.comb(n, k) gives it directly; this simpler layout only lines up while every number has one digit, which holds for 5 rows.
The next row with zip()
Row 1 : [1] Row 2 : [1, 1] Row 3 : [1, 2, 1] Row 4 : [1, 3, 3, 1] Row 5 : [1, 4, 6, 4, 1] Row 6 : [1, 5, 10, 10, 5, 1]
Adding the row to a copy of itself shifted by one place gives the next row in a single line, and this version prints each row as a list.
Try it yourself
Add a line that prints the sum of each row, and check that the sums are 1, 2, 4, 8 and 16.
Edit the program above and press Run, or open it in the full editor to save it and share it. To watch it run line by line, open it in the visualizer.
Related programs
All Python programs · CBSE class 12 practical file · Python exercises