代码提示“TypeError: 'int'对象不可调用”

-3 投票
1 回答
35 浏览
提问于 2025-04-12 22:43

这是代码:

print ("____________________________")
            print ("Advanced calculator selected")
            print ("Experimental! May break.")
            print ("NOTE: Does not work with variables... yet.")
            print ("Key:", "\"()\" mean parenthesis", "\"^\" mean exponent", "\"*\" means multiplication", "\"/\" means division", "\"+\" means addition", "\"-\" means subtraction", sep="\n  ")
            option = "3(5+3)" #input("Equation to solve:").strip()
            option2 = list(option)
            count = -1
            c = True
            while count < len(option2) - 1:
                if c is True:
                    count += 1
                    c = False
                elif c is False:
                    c = True
                if option2[count] == " ":
                    option2.pop(count)
                    count -= 1
                    continue
                elif option2[count] in [0,1,2,3,4,5,6,7,8,9] and option2[count + 1] == "(":
                    option2.insert(count + 1, "*")
                    count += 1
                elif option2[count] in ["(", ")", "*", "/", "+", "-"]:
                    continue
                elif option2[count] == "^":
                    option2.pop(count)
                    option2.insert(count, "**")
                elif str(option2[count]).isalpha() is True:
                    print ("Option not recognized, restarting")
                    counting.Calculator.Advanced()
                else:
                    continue
            print (option2)
            answer = "".join(option2)
            print (answer.isascii())
            answer = eval(str(answer))
            print (answer)
            input()

我搞不懂为什么会出现这个错误。它应该只是把option里的那个公式计算成一个数字,但现在却报错了。

我试过用str(),也试过map(),但我完全不知道哪里出问题了,ChatGPT也没帮上忙,函数的文档也没解释清楚。

1 个回答

-2

每个option2里的元素都是字符串。这意味着这个判断永远不会成立:

                elif option2[count] in [0,1,2,3,4,5,6,7,8,9] and option2[count + 1] == "(":
                    option2.insert(count + 1, "*")
                    count += 1

相反,你想知道这个字符串里是否包含ASCII数字:

                elif option2[count].isdigit() and option2[count + 1] == "(":
                    option2.insert(count + 1, "*")
                    count += 1

我不太明白你的c标志想要做什么,但看起来没什么意义。为什么不直接用更符合Python风格的方法呢:

for char in option:

如果需要的话,你可以构建一个新的字符串来进行评估,虽然eval本身是有风险的。

撰写回答