我的函数有返回语句,为什么我会收到这个错误?类型错误:只能将 str不是“NoneType”连接到 str

问题描述

方法是将输入从中缀转换为后缀的类的一部分。一个示例输入是:"11.897/3.4+9.2-0.4*6.9/12.6-16.7="

我在主方法 (getPostFix) 下面有一些辅助方法

我不明白为什么代码 result += ipop 会导致错误。我在后面的代码中使用了相同的代码片段,所以也许我也必须修复这些实例。我阅读了一些其他答案,其中的答案似乎是在问 OP - “如果这个函数返回 False 怎么办?”但是哪些功能以及他们为什么要这样做?

    def getPostFix(self):

        result = ""

        # stack used to create postfix string
        self.stack = MyStack()

        input_string = self.getinput()
        input_string_split = [x for x in re.split("(\d*\.?\d*)",input_string) if x != '']

        for i in input_string_split:

            if isOperand(i):
                result += i

            elif isOperator(i):
                while True:
                    topItem = self.stack.getTop()
                    if self.stack.size == 0 or topItem == '(':
                        self.stack.push(i)
                        break
                    else:
                        precedence_i = getPrecedence(i)
                        precedence_topItem = getPrecedence(topItem)

                        if precedence_i > precedence_topItem:
                            self.stack.push(i)
                            break
                        else:
                            ipop = self.stack.pop()
                            result += ipop
                            #result += self.stack.pop()

            elif i == '(':
                self.stack.push(i)

            elif i == ')':
                ipop = self.stack.pop()

                while ipop != '(':
                    result += ipop
                    ipop = self.stack.pop()

            elif i == '=':
                ipop = self.stack.pop()
                result += ipop
                #result += self.stack.pop()

        while not self.stack.size == 0:
            ipop = self.stack.pop()
            result += ipop


def isOperand(c):
    return c >= '0' and c <= '9'

operators = "+-*/^"
        
def isOperator(c):
    return c in operators

def getPrecedence(c):
    result = 0

    for i in operators:
        result += 1

        # because + - and */ have the same value
        # these if statements will set their value equal to each other
        # for,example when I get to -,the result count is 2,but I subtract 1 to get 1
        # which is the same result count as +.
        if i == c:
            if c in '-/':
                result -= 1
            break

    return result

这是错误代码

Traceback (most recent call last):
  File " ",line 9,in <module>
    print(calc)
  File " ",line 23,in __str__
    theCalc += 'Postfix input is: ' + self.getPostFix() + '\n'
  File " ",line 71,in getPostFix
    result += ipop
TypeError: can only concatenate str (not "nonetype") to str

解决方法

因为有时您会在可迭代对象的末尾弹出并返回 None,请尝试替换

的所有行
result += ipop

result += ipop if ipop else ""  # Handles None cases and returns empty string.