我试图运行这段代码:
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)
这段代码有什么问题?
score1 + score2
会进行字符串加法,否则您会收到错误。您需要用逗号分隔:
score1,score2 = input ("Enter two scores separated by a comma:").split(",")
但请注意,
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
>>>
输入作为单个字符串到达。但 Python 在处理字符串时具有人格分裂:它可以将它们视为单个字符串值,也可以视为字符列表。当您尝试将其分配给
score1,score2
时,它决定您需要一个字符列表。显然你输入了两个以上的字符,所以它说你的字符太多了。
其他答案对于做你真正想做的事情有非常好的建议,所以我不会在这里重复。
>>>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
如果您使用 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.
我在尝试访问元组值时遇到了这个问题。
您可以使用它来获取从
get_or_create
返回的元组的第一个值:
user, _ = User.objects.get_or_create(
...
)
# email = user.email
# ...