简体   繁体   中英

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. The function should then return the result of that formula. For example, for the input "2 + 3" the function should return 5.

A string is considered a valid formula if it has the format. Note that operator and integer are separated by whitespace. 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: ." 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." 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: +, -, *, /." If the second integer is zero and the operator is /, the function should raise a ZeroDivisionError with the message "Division by zero not possible."

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. 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. I'm assuming something in my approach is off, maybe the order that the try: except blocks are written in? 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)

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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