Book a free demo

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

  1. Each row starts and ends with 1. The numbers in between are the sum of the two numbers above them.
  2. The program builds each row from the last one. rows[-1] is the most recent row.
  3. 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.
See the Python path โ†’

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

All 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

For a childโ€™s class, please have a parent or guardian send the enquiry. Avoid sharing passwords or sensitive personal details.

Weโ€™ll use your details only to respond to this request.

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.

All free games โ†’
Chat on WhatsApp
Esc

Try