2013-09-30 55 views
1

我是一名python初學者。我試圖運行此代碼:當我召喚main()我得到這個ValueErrorpython valueerror:太多值來解壓

def main(): 
    print (" This program computes the average of two exam scores . ") 
    score1,score2 = input ("Enter two scores separated by a comma:") 
    average = (score1 + score2)/2.0 
    print ("The average of the score is : " , average) 

ValueError: too many values to unpack (expected 2) 

什麼是錯的代碼?

+2

@musical_coder:除非你確定OP沒有使用Python 3,否則不要試圖從打印函數中刪除'()'。 – geoffspear

回答

7
  1. 您需要拆分你接收輸入,因爲它到達都在同一個字符串
  2. 然後,你需要將它們轉換爲數字,因爲這個詞score1 + score2會做字符串此外,否則,你會得到一個錯誤。
5

您需要拆分的逗號:

score1,score2 = input ("Enter two scores separated by a comma:").split(",") 

然而要注意score1score2仍將字符串。您需要使用floatint(取決於您需要的號碼類型)將它們轉換爲數字。

參見一個例子:

>>> score1,score2 = input("Enter two scores separated by a comma:").split(",") 
Enter two scores separated by a comma:1,2 
>>> score1 
'1' 
>>> score1 = int(score1) 
>>> score1 
1 
>>> score1 = float(score1) 
>>> score1 
1.0 
>>> 
2

的輸入到達作爲單個字符串。但是對於字符串,Python具有分裂的個性:它可以將它們視爲單個字符串值或字符列表。當你試圖將它分配給score1,score2時,它決定你想要一個字符列表。顯然你輸入了兩個以上的字符,所以它說你有太多。

其他答案有非常好的建議做你真正想要的,所以我不會在這裏重複他們。

相關問題