在我正在使用的Python教程书中,我输入了一个示例同时分配。当我运行程序时,我得到了前面提到的 ValueError ,但不明白为什么。
这是代码:
#avg2.py
#A simple program to average two exam scores
#Illustrates use of multiple input
def main():
print("This program computes the average of two exam scores.")
score1, score2 = input("Enter two scores separated by a comma: ")
average = (int(score1) + int(score2)) / 2.0
print("The average of the scores is:", average)
main()
这是输出。
>>> import avg2
This program computes the average of two exam scores.
Enter two scores separated by a comma: 69, 87
Traceback (most recent call last):
File "<pyshell#4>", line 1, in <module>
import avg2
File "C:\Python34\avg2.py", line 13, in <module>
main()
File "C:\Python34\avg2.py", line 8, in main
score1, score2 = input("Enter two scores separated by a comma: ")
ValueError: too many values to unpack (expected 2)
从提示信息来看,您忘记打电话了str.split https://docs.python.org/3/library/stdtypes.html#str.split在第8行末尾:
score1, score2 = input("Enter two scores separated by a comma: ").split(",")
# ^^^^^^^^^^^
这样做会在逗号上分割输入。请参阅下面的演示:
>>> input("Enter two scores separated by a comma: ").split(",")
Enter two scores separated by a comma: 10,20
['10', '20']
>>> score1, score2 = input("Enter two scores separated by a comma: ").split(",")
Enter two scores separated by a comma: 10,20
>>> score1
'10'
>>> score2
'20'
>>>
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)