Book a free demo

Beginner ยท ages 9+ ยท accumulator ยท for loop ยท sum

Add up the numbers 1 to 100 in Python.

Add 1 + 2 + 3 + ... + 100, and check the answer with a formula.

The program

Press Run to see what it prints. Change anything you like, then run it again.

total = 0
for n in range(1, 101):
    total = total + n
print("The sum is", total)
print("Check with the formula:", 100 * 101 // 2)
print("Using sum():", sum(range(1, 101)))
The sum is 5050
Check with the formula: 5050
Using sum(): 5050

How it works

  1. total starts at 0 and grows each time round the loop. This pattern is called an accumulator.
  2. The story goes that the mathematician Gauss, as a schoolboy, found this sum quickly by pairing 1 with 100, 2 with 99 and so on: 50 pairs of 101, which is 5,050.
  3. sum() adds up a list or range for you. // is division that gives a whole number.
See the Python path โ†’

Try this

  • Add up only the even numbers.
  • Add up the squares: 1, 4, 9, ... up to 100.
  • Find the formula for the sum from 1 to any n.

Stuck on an error? Read how to debug Python.

Similar ideas

More programs

All programs โ†’

FAQ

Add up the numbers 1 to 100: questions

What does the add up the numbers 1 to 100 program do?

Add 1 + 2 + 3 + ... + 100, and check the answer with a formula. It prints: The sum is 5050 / Check with the formula: 5050 / Using sum(): 5050

Which Python ideas does it use?

accumulator, for loop, sum. Beginner level, suitable from about age 9.

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?

Add up only the even numbers. Add up the squares: 1, 4, 9, ... up to 100. Find the formula for the sum from 1 to any n.

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