为什么我会收到TypeError: cannot unpack non-iterable builtin_function_or_method object错误信息?

5

我刚开始学习编程,选择了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"))

类型错误:无法对非可迭代的内置函数或方法对象进行解包


2
y.split in the second function isn't instantiated. You have to add parentheses to the end like this: y.split() - Mark Moretto
1
未来问题建议:请在异常信息中包含您获得的堆栈信息。 - LhasaDad
我猜测这个问题应该被移除。很明显异常是在哪里抛出的,需要调用split方法。 - Vadim Shkaberda
1个回答

5
你在y.split后面忘记了括号,因此你试图解构方法split而不是它的实际结果。

正确的写法是:

x, op, num1, equal, num2 = y.split()

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接