This example will teach us how to print the Pascal triangle of the given number of rows in Python.
Source Code
#! /usr/bin/env python3
# -*- coding: utf-8 -*-
n = int(input("Enter the number of rows: "))
a = [[0 for row in range(0, n)] for col in range(0, n)]
for i in range(0, n):
for j in range(0, n):
if j == 0 or j == i:
a[i][j] = 1
else:
a[i][j] = a[i - 1][j - 1] + a[i - 1][j]
for i in range(0, n):
print(" "*(n - i), end=" ", sep=" ")
for j in range(0, i+1):
print("{0:5}".format(a[i][j]), end=" ", sep=" ")
print()
Output:
Enter the number of rows: 4
1
1 1
1 2 1
1 3 3 1
Enter the number of rows: 6
1
1 1
1 2 1
1 3 3 1
1 4 6 4 1
1 5 10 10 5 1