gpt4 book ai didi

python - 为什么我收到 TypeError : cannot unpack non-iterable builtin_function_or_method object?

转载 作者:行者123 更新时间:2023-12-01 15:21:28 24 4
gpt4 key购买 nike

我是编码新手,我从 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"))

TypeError: cannot unpack non-iterable builtin_function_or_method object

最佳答案

你忘记了 y.split 后面的括号,所以你试图解压方法 split而不是它的实际结果。

它应该是

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

关于python - 为什么我收到 TypeError : cannot unpack non-iterable builtin_function_or_method object?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59116878/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com