2017-08-30 67 views
-5

我想写一个程序,将一起添加一系列用户输入的数字,直到用户键入0,然后显示所有输入数字的总数。这是我有和IM努力修复它卡住这

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) 
+0

你还没有解释什么坏了。 –

+0

请解释什么是错的。你期待什么输出?你得到了什么实际输出/错误? –

+0

请说明问题。发生什么事?什么不起作用?你有什么想要做的?这个问题应该对问题有一个清楚的解释。但就实际问题而言,请仔细阅读您的代码,并在每一行上思考发生了什么,何时向用户提出要求等等。您应该看到问题。或者得到一个调试器并逐行运行它。 –

回答

0

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

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

+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)