Zig*_*ggy 6 python input iterable-unpacking
在我正在使用的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()
Run Code Online (Sandbox Code Playgroud)
这是输出.
>>> 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)
Run Code Online (Sandbox Code Playgroud)
根据提示信息判断,您忘记str.split在第8行结束时致电:
score1, score2 = input("Enter two scores separated by a comma: ").split(",")
# ^^^^^^^^^^^
Run Code Online (Sandbox Code Playgroud)
这样做会将输入拆分为逗号.请参阅下面的演示:
>>> 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'
>>>
Run Code Online (Sandbox Code Playgroud)