python valueerror:解压缩的值太多了

时间:2013-09-30 15:48:32

标签: python python-3.x

我是一名蟒蛇初学者。我试图运行这段代码:

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 )

当我召唤main()时,我得到了这个ValueError

ValueError: too many values to unpack (expected 2)

这段代码有什么问题?

5 个答案:

答案 0 :(得分:14)

  1. 您需要拆分您收到的输入,因为它全部到达一个字符串
  2. 然后,您需要将它们转换为数字,因为术语score1 + score2将执行字符串添加,否则您将收到错误。

答案 1 :(得分:9)

你需要在逗号上分开:

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 :(得分:4)

输入作为单个字符串到达​​。但是当涉及字符串时,Python具有分裂的个性:它可以将它们视为单个字符串值,或者作为字符列表。当您尝试将其分配给score1,score2时,它决定您需要一个字符列表。显然你输入了两个以上的字符,所以它说你有太多了。

其他答案对于做你真正想要的事情有很好的建议,所以我不会在这里重复。

答案 3 :(得分:0)

如果您使用args并在运行文件时提供较少的值,则会显示此错误。

**要纠正这些错误,以提供正确的值**

from sys import argv

one, two, three,four,five = argv

c=input("Enter the coffee you need?: ")

print("File Name is ",one)

print("First you need ",two)

print("The you need",three)

print("Last you need",four)

print("Last but not least you need",five)

print(f"you need above mentioned items to make {c}.")


While running code give it like this: **python hm5.py milk coffeepowder sugar water**

 milk == two

 coffeepowder ==three

 sugar == four

 water == five 

 one == file name (you don't need to give it while running



My output:
Enter the coffee you need?: filter coffee

First you need  milk

The you need coffeepowder

Last you need sugar

Last but not least you need water

you need above mentioned items to make filter coffee.

答案 4 :(得分:0)

>>>number1,number2 = input("enter numbers: ").split(",")
enter numbers: 1,2
>>> number1
'1'
>>> number2
'2'

然后您可以将其转换为整数

>>> number1 = int(number1)
>>> number2 = int(number2)
>>> average = (number1+number2)/2.0
>>> average
1.5