Python Program to Print Pascal Triangle

This is a Python Program to print the pascal’s triangle for n number of rows given by the user.

Problem Description

The program takes a number n and prints the pascal’s triangle having n number of rows.

Problem Solution

1. Take in the number of rows the triangle should have and store it in a separate variable.
2. Using a for loop which ranges from 0 to n-1, append the sub-lists into the list.
3. Then append 1 into the sub-lists.
4. Then use a for loop to determine the value of the number inside the triangle.
5. Print the Pascal’s triangle according to the format.
6. Exit.

Program/Source Code

Here is source code of the Python Program to print the pascal’s triangle for n number of rows given by the user. The program output is also shown below.

n=int(input("Enter number of rows: "))
a=[]
for i in range(n):
    a.append([])
    a[i].append(1)
    for j in range(1,i):
        a[i].append(a[i-1][j-1]+a[i-1][j])
    if(n!=0):
        a[i].append(1)
for i in range(n):
    print("   "*(n-i),end=" ",sep=" ")
    for j in range(0,i+1):
        print('{0:6}'.format(a[i][j]),end=" ",sep=" ")
    print()
Program Explanation

1. User must enter the number of rows that the Pascal’s triangle should have.
2. The for loop is used to append sub-lists into an empty list defined earlier.
3. Then 1 is appended into all the sub-lists.
4. The for loop is used to determine the value of the number inside the triangle which is the sum of the two numbers above it.
5. The other for loop is used to print the Pascal’s triangle according to the format.

advertisement
advertisement
Runtime Test Cases
Case 1:	
Enter number of rows: 3
               1 
            1      1 
         1      2      1 
 
Case 2:
Enter number of rows: 4
                  1 
               1      1 
            1      2      1 
         1      3      3      1

Sanfoundry Global Education & Learning Series – Python Programs.

To practice all Python programs, here is complete set of 150+ Python Problems and Solutions.

Sanfoundry Certification Contest of the Month is Live. 100+ Subjects. Participate Now!

If you find any mistake above, kindly email to [email protected]

advertisement
advertisement
Subscribe to our Newsletters (Subject-wise). Participate in the Sanfoundry Certification contest to get free Certificate of Merit. Join our social networks below and stay updated with latest contests, videos, internships and jobs!

Youtube | Telegram | LinkedIn | Instagram | Facebook | Twitter | Pinterest
Manish Bhojasia - Founder & CTO at Sanfoundry
Manish Bhojasia, a technology veteran with 20+ years @ Cisco & Wipro, is Founder and CTO at Sanfoundry. He lives in Bangalore, and focuses on development of Linux Kernel, SAN Technologies, Advanced C, Data Structures & Alogrithms. Stay connected with him at LinkedIn.

Subscribe to his free Masterclasses at Youtube & discussions at Telegram SanfoundryClasses.