简体   繁体   English

编写一个在 python 中捕获多个异常的 function

[英]writing a function that catches multiple exceptions in python

I am required to write a function that takes a simple mathematical formula as a string as an argument.我需要编写一个 function ,它将一个简单的数学公式作为字符串作为参数。 The function should then return the result of that formula.然后 function 应该返回该公式的结果。 For example, for the input "2 + 3" the function should return 5.例如,对于输入“2 + 3”,function 应返回 5。

A string is considered a valid formula if it has the format.如果字符串具有格式,则将其视为有效公式。 Note that operator and integer are separated by whitespace.请注意,运算符和 integer 由空格分隔。 A valid operator is either +, -, * or / If a string doesn't consist of three parts (integer operator integer), the function should raise a ValueError with the message "Formula must be of the following format: ."有效的运算符是 +、-、* 或 / 如果字符串不包含三个部分(整数运算符整数),则 function 应引发 ValueError 并显示消息“公式必须为以下格式:.”。 If the first part or the last part of the input string can't be converted to integers, the function should raise a ValueError with the message "Expected two integers."如果输入字符串的第一部分或最后一部分无法转换为整数,则 function 应引发 ValueError 并显示消息“预期两个整数”。 If the second part of the string is not one of the valid operators, the function should raise a ValueError with the message "Invalid operator ''. Expected one of these operators: +, -, *, /."如果字符串的第二部分不是有效运算符之一,则 function 应引发 ValueError 并显示消息“无效运算符 ''。应使用以下运算符之一:+、-、*、/。” If the second integer is zero and the operator is /, the function should raise a ZeroDivisionError with the message "Division by zero not possible."如果第二个 integer 为零且运算符为 /,则 function 应引发 ZeroDivisionError 并显示消息“无法除零”。

So far I've managed to split the string by whitespace and convert the [0] and [2] indexes to integers to be used in solving the respective mathematical equations, and I've also written a try: except: block that successfully catches invalid operators and returns the desired error message.到目前为止,我已经设法通过空格分割字符串并将 [0] 和 [2] 索引转换为整数以用于求解相应的数学方程,并且我还编写了一个 try: except: 成功捕获的块无效的运算符并返回所需的错误消息。 My problem is going on to accommodate the other exceptions as outlined in the conditions, although I've written code that attempts to catch the exceptions and print the relevant error messages, it isn't working and I'm still getting the default internal python error messages.我的问题是继续适应条件中概述的其他异常,尽管我编写了尝试捕获异常并打印相关错误消息的代码,但它不起作用,我仍然得到默认的内部 python错误信息。 I'm assuming something in my approach is off, maybe the order that the try: except blocks are written in?我假设我的方法中的某些东西是关闭的,也许是 try: except 块的写入顺序? something with the indenting?缩进的东西? I'm new to this so any pointers or advice would be much appreciated.我对此很陌生,因此非常感谢任何指示或建议。

def formula_from_string(formula):
    valid_operators = '+-*/'
    chopped=formula.split()
    equa=int(chopped[0]),chopped[1],int(chopped[2])
    subtraction=equa[0]-equa[2]
    addition=equa[0]+equa[2]
    division=equa[0]/equa[2]
    multiplication=equa[0]*equa[2]
    if chopped[1]=='+':
        return(addition)
    elif chopped[1]=='-':
        return(subtraction)
    elif chopped[1]=='*':
        return(multiplication)
    elif chopped[1]=='/':
        return(division)
    try:
        if chopped[1] not in valid_operators:
            invalid=chopped[1]
            raise ValueError
    except ValueError:
        print('Value Error:')
        return("Invalid operator '"+invalid+"'. Expected one of these operators: +, -, *, /.")
        try:
            if chopped[0] or chopped[2] != int:
                raise ValueError
        except ValueError:
            print('Value Error:')
            return('Expected two integers.')
            try:
                if equa[1]=='/' and equa[2]==0:
                    raise ZeroDivisionError
            except ZeroDivisionError:
                        print('ZeroDivisionError:')
                        return('Division by zero not possible.')
            try:
                if chopped <=1 or chopped >=2:
                     raise ValueError
            except ValueError:
                        print('ValueError:')
                        return('Formula must be of the following format: <integer> <operator> <integer>.')

This code should helps you.这段代码应该可以帮助你。 learn about Regex (Regular Expressions)了解Regex (Regular Expressions)

See Regular expression operations请参见正则表达式操作

import re


def formula_from_string(formula):
    valid_operators = '+-*/'
    pattern = re.compile(r'^(\d+)(?:\s+)?([*/+\-^])(?:\s+)?(\d+)$')

    try:
        if match := pattern.search(formula):
            operator = match.group(2)
            if operator not in valid_operators:
                raise ValueError(f"Invalid operator {repr(operator)}. Expected one of these operators: +, -, *, /.")
        else:
            raise ValueError('Formula must be of the following format: <integer> <operator> <integer>.')

        return eval(formula)  # Safe call
    except (ValueError, ZeroDivisionError) as e:
        print(e)

# Uncomment to see output
# formula_from_string('3 / 2')  # 1.5
# formula_from_string('3 ^ 2')  # ValueError Invalid operator
# formula_from_string('a / 2')  # ValueError Formula must be...
# formula_from_string('3 / 0')  # ZeroDivisionError

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM