Coding Pascal’s Triangle with Python is a fun intermediate-level challenge.
Pascal’s Triangle is a fascinating mathematical structure which contains many patterns. Each element in a row is formed by adding the two elements above it in the preceding row. There are many uses for the triangle in areas such as probability and counting the ways things can be combined (e.g. how many pizza types are possible with 5 available toppings?). Make sure you understand how the triangle is constructed, and then
Write a program which displays every row of Pascal’s Triangle for a given value of
nis the number of rows.
The approach used in my solution below is to build each new row from the previous row using nested for loops resulting in a list of lists. Before looking at my solution, be sure to have a really good go at it yourself. Another approach would be to think about how each term in a given row is generated, and build each row using the appropriate formula. To keep things simpler, the output should be left-aligned. E.g:
1 1 1 1 2 1 1 3 3 1 1 4 6 4 1
Good luck, and I hope you enjoy the challenge. If you want to, let me know how you got on in the comments below.
# Pascal's Triangle def pascal(n): """Returns a 2D list containing rows of Pascal's Triangle up to the nth.""" triangle = [] for i in range(n - 1): new_row =  for j in range(i): new_row.append( triangle[i][j] + triangle[i][j + 1] ) new_row.append(1) triangle.append(new_row) return triangle result = pascal(4) # One way to print out a 2D list for row in result: for item in row: print(item, end=" ") print()
Note that the above solution makes use of 2d lists in Python. These are a surprisingly handy data structure with many uses. You can learn about them in depth by taking my course on LinkedIn Learning, available here: 2d Lists in Python – A Game Based Project
(Please note the above courses are affiliate products, meaning I will receive a commission if you make a purchase using the links on the buttons.)