How to sum numbers from input?

前端 未结 2 1991
天涯浪人
天涯浪人 2021-01-29 13:40

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

相关标签:
2条回答
  • 2021-01-29 14:06

    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
    
    0 讨论(0)
  • 2021-01-29 14:10
    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
    
    0 讨论(0)
提交回复
热议问题