← Back to Blog

WHILE Mini Project — Accumulator

The problem...

You need to add up numbers. But you don't know how many. Could be three. Could be thirty.

You keep going until you decide to stop.

The idea!

while True keeps asking. Each number gets added to a running total. When the user types "stop"break fires — the total is printed.

Your mission

Ask the user for numbers one at a time. Add each one to a running total. Stop when the user types "stop". Print the total and how many numbers were entered.

The solution

total = 0
count = 0

while True:
    entry = input("Enter a number (or 'stop'): ")
    if entry == "stop":
        break
    total += int(entry)
    count += 1

print(f"Numbers entered: {count}")
print(f"Total: {total}")

Test it

# Enter a number (or 'stop'): 10
# Enter a number (or 'stop'): 25
# Enter a number (or 'stop'): 8
# Enter a number (or 'stop'): stop
# Numbers entered: 3
# Total: 43

What's really happening

The loop runs forever — until the user says stop. Every valid entry gets converted to an integer and added to the total. The counter tracks how many entries were made. After break — both are ready to print.

Go further

  • Print the average — total / count — watch out for division by zero if count is 0
  • Add input validation — what happens if the user types a word instead of a number?
  • Track the highest number entered using a second variable

What you should understand now

  • while True + break — runs until the user decides to stop
  • Two counters — total and count — both defined before, updated inside, used after
  • int(entry) converts the string input to a number before adding
  • The exit condition lives inside the loop — not outside it
[ login to bookmark ] // copied! 22 views · 1 min
// resources
Exercise accumulator.py
← prev while also has a plan B next → WHILE Mini Project — Rock, Paper, Scissors
// 0 comments
// No comments yet. Be the first.
// leave a comment

// Your comment will appear after approval.