ValueError: too many values to unpack (expected 2)
60,101
The above code will work fine on Python 2.x. Because input
behaves as raw_input
followed by a eval
on Python 2.x as documented here - https://docs.python.org/2/library/functions.html#input
However, above code throws the error you mentioned on Python 3.x. On Python 3.x you can use the ast
module's literal_eval()
method on the user input.
This is what I mean:
import ast
def main():
print("This program computes the average of two exam scores.")
score1, score2 = ast.literal_eval(input("Enter two scores separated by a comma: "))
average = (int(score1) + int(score2)) / 2.0
print("The average of the scores is:", average)
main()
Author by
Ziggy
Updated on August 03, 2022Comments
-
Ziggy almost 2 years
In the Python tutorial book I'm using, I typed an example given for simultaneous assignment. I get the aforementioned ValueError when I run the program, and can't figure out why.
Here's the code:
#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()
Here's the output.
>>> 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)
-
kindall about 10 yearsHuh, never considered using
literal_eval
for that!