I'm getting an off by one error in my program

I’ve got a program which asks the user to enter an integer and if he wants to quit then enter the sentinel value of -1.

But when I read the final output, which is the final sum of the numbers entered, the sum is off by one.

Here is my code:

sum = 0
number = 0

print("Enter an integer or -1 to end.")

while number != -1:
    number = int(input("Enter an integer: "))
    sum = sum + number
print("The sum is", sum)
    type or paste code here

I think the problem is when I hit -1 which is the sentinel value, that -1 is being added to the total. I think that is causing the off by one error.

How do I fix it I’m trying to figure that out.

You’re exactly right!

So, very good question, how do you fix it? There are a few options.

One is to check for -1 between receiving the number and adding it to the sum:

while "moar numbers plsthx": # infinite loop
    number = int(input("Enter an integer: "))
    if number == -1: break
    sum = sum + number

The break statement is perfect for these sorts of mid-loop checks.

Another technique is to treat the input request as part of the loop header.

while (number := int(input("Enter a number: "))) != -1:
    sum = sum + number

This can get unwieldy if the prompt is long, but it’s also a very elegant way to express the idea of “ask for numbers until the user enters -1”.

A third option is to simply accept that you’re going to be adding -1 at the end, and subtract it out afterwards:

while number != -1:
    number = int(input("Enter a number: "))
    sum = sum + number
sum = sum - number # Exclude the sentinel from the sum

Be aware that sometimes this isn’t going to work. When you’re just adding and subtracting integers, it’s nice and easy, but if you were, say, multiplying and dividing floats, that might give a slightly different result.

There are other strategies too, so feel free to play around and try things out!

Thank You for your help. The break statement works perfect.
And the books don’t show this?

They probably do, but maybe a bit later on? But like everything in programming, there are multiple ways to do things, so you choose the one that’s right for you.

  1. while True:...break is a standard loop-and-a-half idiom. Does our tutorial not mention it? I suspect it is in one of the FAQs somewhere.

  2. If you allow addition of -2, -3, …, why disallow addition of -1? Why not 0 to end entry?