Skip to content Skip to sidebar Skip to footer

How To Sum Numbers From Input?

I am working on the following problem. Write a program that continually prompts for positive integers and stops when the sum of numbers entered exceeds 1000. But my code stop earl

Solution 1:

x = 0
total = 0
sum = 0
while sum <= 1000:
    x = int(input("Enter an integer:"))
    if x<0:
        print("Invalid negative value given")
        break
    sum += x


First:

if sum >= 1000:
    ...
elif sum < 1000:
    ...

is redundant, because if you chek for sum >= 1000, and the elif is reached, you aready know, that the condition was False and therefore sum < 1000 has to be true. So you could replace it with

if sum >= 1000:
    ...
else:
    ...


Second:
You want to use x to check, whether the input is negative. Until now, you were simpy increasing it by one each time. Instead, you should first assing the input to x, and then add this to sum. So do it like this:

x = int(input("Enter an integer:"))
if x<0:
    break
sum += x

Solution 2:

In case you want to stop as soon as you encounter the negative number.

x = 0
total = 0
sum = 0
while (sum <= 1000):
    x = (int(input("Enter an integer:"))
    if (x < 0):
        break
    else:
        sum += x

Post a Comment for "How To Sum Numbers From Input?"