# Align the numbers in Pascal's triangle

#1

Hi,

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.

Thanks!

``````def pascal_triangle(row):
if row == 1:
print_row([1], 1)
return [1]
else:
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])
current_row.append(1)

print_row(current_row, row)
return current_row

def print_row(lst, row):
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: "))
pascal_triangle(number_of_rows)

``````

#2

you could use `.format()`:

https://pyformat.info/

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

#3

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