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 cod
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
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