python valueerror:解压缩的值太多了

DAV*_*VID 6 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 )
Run Code Online (Sandbox Code Playgroud)

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

ValueError: too many values to unpack (expected 2)
Run Code Online (Sandbox Code Playgroud)

这段代码有什么问题?

wim*_*wim 14

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


iCo*_*dez 9

你需要在逗号上拆分:

score1,score2 = input ("Enter two scores separated by a comma:").split(",")
Run Code Online (Sandbox Code Playgroud)

但是请注意,score1并score2仍将是字符串.您需要使用float或将它们转换为数字int(取决于您想要的数字类型).

看一个例子:

>>> 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
>>>
Run Code Online (Sandbox Code Playgroud)