How to sum numbers from input?

百般思念 提交于 2020-02-26 04:16:45

问题


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 early if a negative integer is entered.

The numbers will not sum.

My code:

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

回答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



回答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


来源:https://stackoverflow.com/questions/39951024/how-to-sum-numbers-from-input

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!