I keep getting this error:
x, y, z = expression.split(" ")
ValueError: not enough values to unpack (expected 3, got 1)
This is my code:
expression = input("Expression: ")
# Parse variables.
x, y, z = expression.split(" ")
new_x=float(x)
new_z=float(z)
#calculate
if y == " ":
result = new_x new_z
if y == "-":
result = new_x - new_z
if y == "*":
result = new_x * new_z
if y == "/":
result= new_x / new_z
print(round(result, 1))
CodePudding user response:
The issue is that the input does not have enough delimited fragments to split into three pieces. You can play with this in the REPL:
>>> x, y, z = "a b c".split(" ")
>>> x
'a'
>>> y
'b'
>>> z
'c'
>>> x, y, z = "a b".split(" ")
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
ValueError: not enough values to unpack (expected 3, got 2)
>>> x, y, z = "a".split(" ")
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
ValueError: not enough values to unpack (expected 3, got 1)
For your use case where you are accepting input, the best bet is to handle this specific exception.
valid_input = false
x, y, z = None, None, None
while not valid_input:
try:
expression = input("Expression: ")
x, y, z = expression.split(" ")
valid_input = true
except ValueError:
print("Invalid input provided. Be sure to provide input with exactly 2 spaces in it!")
... # Continue with the rest of your code
Another way to do this is:
def input_expression(attempt: int = 0) -> [str, str, str]:
if attempt > 3:
raise Exception("Too many invalid attempts. Quitting.")
try:
expression = input("Expression: ")
x, y, z = expression.split(" ")
return x, y, z
except ValueError:
print("Invalid input provided. Be sure to provide input with exactly 2 spaces in it!")
return input_expression(attempt 1)
x, y, z = input_expression()
... # The rest of your code
CodePudding user response:
it means that expression.split(" ")
returns only one value, but since you unpacked its value to three variables x,y,z
, it should return three values. So the problem is actually with your input.