坚持这个

时间:2017-08-30 11:28:57

标签: python

我正在尝试编写一个程序,将用户输入的一系列数字相加,直到用户输入0,然后显示所有输入数字的总和。这就是我所拥有的,我正在努力解决它

print ("Keep inputting numbers above 0 and each one will be added together consecutively. enter a and the total will be displayed on the screen. have fun")

number = input("Input a number")

sum1 = 0

while number >= 1:

    sum1 = sum1 + number

if number <= 0:
    print (sum1) 

2 个答案:

答案 0 :(得分:1)

这是输入数字的更健壮的方法。它检查是否可以添加。此外,我添加了正数和负数。

# -*-coding:Utf-8 -*

print ("Keep inputting numbers different than 0 and each one will be added together consecutively.") 
print ("Enter a and the total will be displayed on the screen. Have fun.")

sum = 0
x = ""

while type(x) == str:
        try:
                x = int(input("Value : "))
                if x == 0:
                        break
                sum += x
                x = ""
        except:
                x = ""
                print ("Please enter a number !")

print ("Result : ", sum)

答案 1 :(得分:0)

如果您使用的是Python 3,则需要说number = int(input("Input a number")),因为input会返回一个字符串。如果您使用的是Python 2,input将适用于数字但有其他问题,最佳做法是说int(raw_input(...))。有关详细信息,请参阅How can I read inputs as integers?

由于您希望用户重复输入数字,因此input循环中还需要while。现在它只运行一次。