Reputation: 123
I am new to coding and I am starting with python. I am trying to make a method that will take an equation and solve for an unknown variable. It works for just one equation (one operator) but didn't work when I tried to make it return value based on an operator.
This worked:
def solveforx(y):
x, add, num1, equal, num2 = y.split()
# convert the strings into ints
num1, num2 = int(num1), int(num2)
# convert the result into a string and join it to the string "x = "
return "x = "+ str(num2 - num1)
print(solveforx("X + 5 = 9"))
This didn't:
def solveforx(y):
x, op, num1, equal, num2 = y.split
num1, num2 = int(num1), int(num2)
if op == "+":
return "x = " + str(num2 - num1)
elif op == "-":
return "x = " + str(num1 + num2)
elif op == "*":
return "x = " + str(num2/num1)
elif op == "/":
return "x = " + str(num1*num2)
else:
return "wrong operator"
print(solveforx("X + 5 = 9"))
TypeError: cannot unpack non-iterable builtin_function_or_method object
Upvotes: 5
Views: 13017
Reputation: 4943
You forgot the parentheses after y.split
, so you tried to unpack the method split
instead of its actual result.
It should be
x, op, num1, equal, num2 = y.split()
Upvotes: 5