我刚开始学习编程,选择了Python作为起点。我正在尝试创建一个方法,可以用于解决方程并计算未知变量。
当只有一个运算符时,它可以工作:
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"))
这个没有:
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"))
类型错误:无法对非可迭代的内置函数或方法对象进行解包
y.split
in the second function isn't instantiated. You have to add parentheses to the end like this:y.split()
- Mark Morettosplit
方法。 - Vadim Shkaberda