Confident ยท ages 12+ ยท lists ยท nested loops ยท patterns
Pascal's triangle in Python.
Print the first eight rows of Pascal's triangle, where each number is the sum of the two above it.
The program
Press Run to see what it prints. Change anything you like, then run it again.
rows = [[1]]
for i in range(7):
last = rows[-1]
new = [1]
for j in range(len(last) - 1):
new.append(last[j] + last[j + 1])
new.append(1)
rows.append(new)
for row in rows:
print(" ".join(str(x) for x in row).center(30)) 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
How it works
- Each row starts and ends with 1. The numbers in between are the sum of the two numbers above them.
- The program builds each row from the last one.
rows[-1]is the most recent row. center(30)pads the line with spaces so the triangle looks like a triangle. Look for patterns: the sums of the rows are 1, 2, 4, 8, ... the powers of 2.
Try this
- Print more rows.
- Add up each row and check it is a power of 2.
- Print only the odd numbers and see the pattern.
Stuck on an error? Read how to debug Python.
Similar ideas
More programs
FAQ
Pascal's triangle: questions
What does the pascal's triangle program do?
Print the first eight rows of Pascal's triangle, where each number is the sum of the two above it. It prints: 1 / 1 1 / 1 2 1 โฆ
Which Python ideas does it use?
lists, nested loops, patterns. Confident level, suitable from about age 12.
How do I run it?
Press Run on this page. To run it on your own computer, install Python 3 and save the code in a file ending in .py. It prints the same thing.
What should I try next?
Print more rows. Add up each row and check it is a power of 2. Print only the odd numbers and see the pattern.
Start a conversation
Want a teacher to guide the learning?
Tell us the learner's age and what they can already do, and we will suggest a starting point. A parent or guardian can make the enquiry.
- Tell us the learnerโs age or grade and goals
- Weโll suggest a suitable class or learning path
- Weโll confirm format, timing and fees with a parent or guardian
Play it, don't just read it
Write some code right now
Free games that need no sign-up. Pick one and play for five minutes.
Pick a game
- Code BuilderThe lines of a Python program are mixed up. Tap them into the rightโฆPlay
- Bug HunterA Python program prints the wrong answer. Find the one line with theโฆPlay
- Predict the OutputRead a short Python program and choose what it prints. Then watch it runโฆPlay
- Code JungleWrite real Python to guide Miko the monkey to every banana. 24 levels:โฆPlay