2017-08-30 68 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)