python 类型错误:不支持的操作数类型,+:’float’ 和 ‘NoneType’

huangapple go评论70阅读模式
英文:

pyhton TypeError: unsupported operand type(s) for +: 'float' and 'NoneType'

问题

如果我输入带括号的表达式,它只计算括号内的内容,而不计算括号前后的内容。如果我输入两个带括号的表达式,它会返回 None。你可以在代码中看到这一点。
英文:

`If I enter input with parentheses it resolves only what is inside the parentheses and not what is after or before, if I enter two expressions with parentheses it returns None. you can see it in the code.

def divide(a, b):
    return a/b
def pow(a, b):
    return a**b
def addA(a, b):
    return a+b
def subA(a, b):
    return a-b
def mul (a, b):
    return a*b

operators = {
  '+': addA,
  '-': subA,
  '*': mul,
  '/': divide,
  '^': pow,


}
def extract_expression(s):
    start = s.index('[')
    end = s.rindex(']')
    while ']' in s:

        return s[start + 1:end]

def calculate(s):
    while '[' in s:
        sub_expression = extract_expression(s)
        result = calculate(sub_expression)
        s = s.replace('[' + sub_expression + ']', str(result))

    if s.isdigit():
        return float(s)

    for c in operators.keys():
        left, operator, right = s.partition(c)
        if operator in operators:
            return operators[operator](calculate(left), calculate(right))

calc = input("Type calculation:\n")
print("Answer: " + str(calculate(calc)))

答案1

得分: 1

问题出在第二步,当他计算2+3.0时,s.isdigit()s是3.0时返回false。这就是为什么3.0从未返回。然后他尝试计算addA(2,None),这导致了错误。

你可以尝试用包括浮点数的自己编写的检查替换s.isdigit()

替换s.isdigit()的函数可以如下所示:

def is_float_digit(n: str) -> bool:
    try:
        float(n)
        return True
    except ValueError:
        return False

整个代码可以如下所示:

def divide(a, b):
    return a/b
def pow(a, b):
    return a**b
def addA(a, b):
    return a+b
def subA(a, b):
    return a-b
def mul (a, b):
    return a*b

operators = {
  '+': addA,
  '-': subA,
  '*': mul,
  '/': divide,
  '^': pow,
}


def is_float_digit(n: str) -> bool:
    try:
        float(n)
        return True
    except ValueError:
        return False

def extract_expression(s):
    start = s.index('[')
    end = s.rindex(']')
    while ']' in s:
        return s[start + 1:end]

def calculate(s):
    while '[' in s:
        sub_expression = extract_expression(s)
        result = calculate(sub_expression)
        s = s.replace('[' + sub_expression + ']', str(result))

    if is_float_digit(s):
        return float(s)

    for c in operators.keys():
        left, operator, right = s.partition(c)
        if operator in operators:
            return operators[operator](calculate(left), calculate(right))

calc = input("输入计算表达式:\n")
print("答案: " + str(calculate(calc)))

希望这有所帮助。

英文:

Problem is during the second step when he calculates 2+3.0 -> s.isdigit() when s is 3.0 returns false.
This is why 3.0 is never returned. Then he tries to calculate addA(2,None) which results in your error.

What you can try is to replace s.isdigit() with your own written check which includes floats.

The function to replace s.isdigit() can look like this:

def is_float_digit(n: str) -> bool:
    try:
        float(n)
        return True
    except ValueError:
        return False

The entire code could look like this:

def divide(a, b):
    return a/b
def pow(a, b):
    return a**b
def addA(a, b):
    return a+b
def subA(a, b):
    return a-b
def mul (a, b):
    return a*b

operators = {
  '+': addA,
  '-': subA,
  '*': mul,
  '/': divide,
  '^': pow,
}


def is_float_digit(n: str) -> bool:
    try:
        float(n)
        return True
    except ValueError:
        return False

def extract_expression(s):
    start = s.index('[')
    end = s.rindex(']')
    while ']' in s:

        return s[start + 1:end]

def calculate(s):
    while '[' in s:
        sub_expression = extract_expression(s)
        result = calculate(sub_expression)
        s = s.replace('[' + sub_expression + ']', str(result))

    if is_float_digit(s):
        return float(s)

    for c in operators.keys():
        left, operator, right = s.partition(c)
        if operator in operators:
            return operators[operator](calculate(left), calculate(right))

calc = input("Type calculation:\n")
print("Answer: " + str(calculate(calc)))

huangapple
  • 本文由 发表于 2023年2月6日 05:49:47
  • 转载请务必保留本文链接:https://go.coder-hub.com/75355763.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定