Search code examples
pythonpython-3.xpascals-triangle

Print Pascal's triangle in Python properly


I have coded a Pascal's triangle program in Python, but the triangle is printing as a right angled triangle.

n = int(input("Enter the no. of rows: "))
for line in range(1, n + 1):
    c = 1
    x = n
    y = line

    for i in range(1, line + 1):

        print(c, end = " ")
        c = int(c * (line - i) / i)
    print(" ")

This gives the output as

Enter the no. of rows: 5
1
1 1
1 2 1
1 3 3 1
1 4 6 4 1

But I want it like this.


Solution

  • You could simply just modify your existing code with 2 modifications -

    1. Before each line, add (n-line) spaces
    2. Center align each of the 1 or 2 digit numbers into a 4 alphabet space (changing this yields interesting skewed results :))
    n=8
    for line in range(1, n + 1):
        c = 1
        x=n
        y=line
        #######
        print("  "*(n-line), end="") # This line adds spaces before each line
        #######
        for i in range(1, line + 1):
            ########
            print(str(c).center(4), end = "") # This center aligns each digit
            ########
            c = int(c * (line - i) / i)
        print(" ")
    
    

    Output

                   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