Align the numbers in Pascal's triangle



I made a program to display Pascal’s triangle using recursion. How would I make the numbers align when I have 19 rows for example? I don’t want to write many if else statements. I would like something simple that aligns the numbers no matter how many digits it has.


def pascal_triangle(row):
    if row == 1:
        print_row([1], 1)
        return [1]
        previous_row = pascal_triangle(row - 1)
        current_row = [1]

        for i in range(1, len(previous_row)):
            current_row.append(previous_row[i - 1] + previous_row[i])

        print_row(current_row, row)
        return current_row

def print_row(lst, row):
    # Padding
    print((number_of_rows - row) * " ", end="")
    # Print all the elements in the list separated by spaces
    for element in lst:
        print(element, end=" ")
    print()  # Move to the next line

number_of_rows = eval(input("Enter the number of rows: "))


you could use .format():

it allows to center, although then you might want to calculate the digits of the largest value.


This topic was automatically closed 7 days after the last reply. New replies are no longer allowed.