簡體   English   中英

編寫一個在 python 中捕獲多個異常的 function

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

我需要編寫一個 function ,它將一個簡單的數學公式作為字符串作為參數。 然后 function 應該返回該公式的結果。 例如,對於輸入“2 + 3”,function 應返回 5。

如果字符串具有格式,則將其視為有效公式。 請注意,運算符和 integer 由空格分隔。 有效的運算符是 +、-、* 或 / 如果字符串不包含三個部分(整數運算符整數),則 function 應引發 ValueError 並顯示消息“公式必須為以下格式:.”。 如果輸入字符串的第一部分或最后一部分無法轉換為整數,則 function 應引發 ValueError 並顯示消息“預期兩個整數”。 如果字符串的第二部分不是有效運算符之一,則 function 應引發 ValueError 並顯示消息“無效運算符 ''。應使用以下運算符之一:+、-、*、/。” 如果第二個 integer 為零且運算符為 /,則 function 應引發 ZeroDivisionError 並顯示消息“無法除零”。

到目前為止,我已經設法通過空格分割字符串並將 [0] 和 [2] 索引轉換為整數以用於求解相應的數學方程,並且我還編寫了一個 try: except: 成功捕獲的塊無效的運算符並返回所需的錯誤消息。 我的問題是繼續適應條件中概述的其他異常,盡管我編寫了嘗試捕獲異常並打印相關錯誤消息的代碼,但它不起作用,我仍然得到默認的內部 python錯誤信息。 我假設我的方法中的某些東西是關閉的,也許是 try: except 塊的寫入順序? 縮進的東西? 我對此很陌生,因此非常感謝任何指示或建議。

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>.')

這段代碼應該可以幫助你。 了解Regex (Regular Expressions)

請參見正則表達式操作

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