2016-04-14 59 views
0

我試圖做一些事情(承認)簡單。我想讓我的函數接受一個輸入,如果它是一個整數,運行幾行(如果它是一個特定命令(完成),則退出循環)如果它是字符串,則輸出錯誤消息。我的問題是,它從來沒有檢測到一個整數,而是總是顯示錯誤消息,除非我退出循環。檢查輸入值是整數,命令,還是隻是壞數據(Python)

#The starting values of count (total number of numbers) 
#and total (total value of all the numbers) 
count = 0 
total = 0 

while True: 
    number = input("Please give me a number: ") 
    #the first check, to see if the loop should be exited 
    if number == ("done"): 
     print("We are now exiting the loop") 
     break 
    #the idea is that if the value is an integer, they are to be counted, whereas 
    #anything else would display in the error message 
    try: 
     int(number) 
     count = count + 1 
     total = total + number 
     continue 
    except: 
     print("That is not a number!") 
     continue 
#when exiting the code the program prints all the values it has accumulated thus far 
avarage = total/count 
print("Count: ", count) 
print("Total: ", total) 
print("Avarage: ", avarage) 

從周圍的代碼有點戳,好像問題出在(數=計+ 1)和(總=總+ 1),但我無法明白。任何幫助不勝感激。

回答

1

你不會將int(number)賦值給任何東西,所以它仍然是一個字符串。

你需要做兩件事。改變你的異常處理來打印實際的錯誤,以便你知道發生了什麼。此代碼執行以下操作。

except Exception as e: 
    print("That is not a number!", e) 
    continue 

輸出:

That is not a number! unsupported operand type(s) for +: 'int' and 'str' 

這意味着要添加字符串和一個整數在一起,你不能這樣做。看你的代碼,你這樣做,在:

try: 
    int(number) <------- This is not doing anything for your program 
    count = count + 1 
    total = total + number 

你認爲這是永久性變動數爲int,這樣你就可以在以後使用它,但它不是。這只是一條線,所以你需要像這樣移動它兩條線:

try: 
    count = count + 1 
    total = total + int(number) 
相關問題