While Loop Help

I know this isn't the right forum for Python but I am hoping someone can help me. I just started picking up Python along with C++. I am having trouble with this simple problem. Here are the codes.

// Program sums a list of positive integers that terminates with a negative integer

1
2
3
4
5
6
7
8
9
10
11
12
int main()
{
    int number = 0, sum = 0;
    cout << "Enter numbers: ";
    while(number >= 0)
    {
        cin >> number;
        sum += number;
    }
    cout << "Sum is: " << sum;
    return 0;
}

// An input of 1 2 3 4 5 -1 produces a sum of 15, which is correct.


// Code in Python produces a sum of 14 for the same input.
// The sentinel value, which is -1, is summed.

1
2
3
4
5
6
number = total = 0
print("Enter numbers: ")
while number >= 0:
    number = eval(input())
    total += number
print("Sum is",total)
Last edited on
I get 14 with both codes.

In both cases you input the number AFTER testing it, so the test is effectively done on the previous number (or whatever you initialised it to for the first).
Topic archived. No new replies allowed.