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.")
print()
while number != -1:
number = int(input("Enter an integer: "))
sum = sum + number
print()
print("The sum is", sum)
type or paste code here

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!

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.