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
totalstarts at 0 and grows each time round the loop. This pattern is called an accumulator.- 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.
sum()adds up a list or range for you.//is division that gives a whole number.
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
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
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
- Predict the OutputRead a short Python program and choose what it prints. Then watch it runโฆPlay
- 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
- Code JungleWrite real Python to guide Miko the monkey to every banana. 24 levels:โฆPlay