11

I am a python beginner . I was trying to run this code :

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 )

when I summon the main() I got this ValueError :

ValueError: too many values to unpack (expected 2)

what is wrong with this code ?

4

5 回答 5

17
  1. 您需要拆分收到的输入,因为它全部在一个字符串中到达
  2. 然后,您需要将它们转换为数字,因为该术语score1 + score2将执行字符串添加,否则您将收到错误消息。
于 2013-09-30T15:50:22.807 回答
11

你需要用逗号分开:

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

但是请注意,score1andscore2仍然是字符串。您需要使用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
>>>
于 2013-09-30T15:50:39.190 回答
4

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

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

于 2013-09-30T15:55:27.420 回答
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.
于 2018-06-20T09:41:56.327 回答
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
于 2019-01-29T09:25:34.223 回答