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 = 0sum = 0whilesum <= 1000:
x = int(input("Enter an integer:"))
if x<0:
print("Invalid negative value given")
breaksum += x
First:
ifsum >= 1000:
...
elifsum < 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
ifsum >= 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:
breaksum += x
Solution 2:
In case you want to stop as soon as you encounter the negative number.
x = 0
total = 0sum = 0while (sum <= 1000):
x = (int(input("Enter an integer:"))
if (x < 0):
breakelse:
sum += x
Post a Comment for "How To Sum Numbers From Input?"