2015-11-23 75 views
-2

嗯,這是一種家庭作業項目,我有點難住。我試圖做str/int轉換。原來的行是allScores.append (int(strScore/10) - 但我發現/ 10是多餘的,因爲我想附加值本身。我正在調試一個故意充滿簡單等級計算缺陷的程序。ValueError:int()與基數10的無效文字:'完成'

MAX_SCORE = 10 
MIN_SCORE = 0 

def GetValidInput (prompt): 
    strScore = input (prompt) # Added() to isdigit 
    while (not strScore.isdigit() and strScore != "done") or \ 
      (strScore.isdigit() and \ 
      (int(strScore) < MIN_SCORE or int(strScore) > MAX_SCORE)):  #Added int() as is it was comparing strings and numbers -- Changed AND  to OR 
     if (strScore.isdigit()): 
      print ("Please enter a number between %0d and %0d." \ 
        % (MIN_SCORE, MAX_SCORE), end=' ') 
     else: 
      print ("Please enter only whole numbers.", end=' ') 
     strScore = input (prompt) 
    return strScore 

allScores = [ ] 
strScore = GetValidInput ("Enter HW#" + str(len(allScores)) + "  score: ") #Added str(), as is printing a string 
while (strScore != "done"): 
    strScore = GetValidInput ("Enter HW#" + str(len(allScores)) + "  score: ") # Fixed GetvalidInput to GetValidInput -- Added str() to  allScores to work in string -- Changed line place with the one below 
    allScores.append (int(strScore)) # Fixed MAXSCORE to MAX_SCORE --  Added int() as it was comparing string strScore to an Integer --  Changed line place with the one above -- Removed 
    print(str(allScores)) 

出於某種原因,我不斷收到
ValueError: invalid literal for int() with base 10: 'done' ,但我一定要值追加到列表中,並得到一個平均值。有沒有辦法做到這一點,而不添加另一個IF?在這裏仍然學習python和基本的編程。

任何有幫助的建議嗎?

+2

您的'GetValidInput()'函數保證返回''done''。然後你嘗試將其轉換爲'int()'。 – TigerhawkT3

+0

我需要一個整數列表,但我需要完成循環。你會建議什麼?我查看了你說的話並刪除了int(),但後來似乎遇到了一個總結列表中數字的問題。 除非我可以使它工作 pctScore = sum(allScores)//(len(allScores)* 100) – Adrian

回答

0

只需稍後退出int()即可。將所有內容附加爲一個字符串,然後在完成循環後,最後一個元素('done')轉換爲整數(map(),理解,無論如何)。

while strScore != "done": 
    strScore = GetValidInput("Enter HW#{}  score: ".format(len(allScores))) 
    allScores.append(strScore) 
    print(allScores) 
allScores.pop() 
allScores = list(map(int, allScores)) 
+0

謝謝,剛剛完成了程序的其餘部分,並且這部分被更大的程序所接受。非常感激。 – Adrian

+0

@Adrian - 樂於助人。如果您願意,您可以將此答案標記爲已通過單擊其分數下方的複選標記來解決問題。 – TigerhawkT3

相關問題