python 簡易計算器(只能計算加減乘除和括號)


import re


# 格式化字符串函數(消除一些錯誤的格式)
def format_string(string):
    # 一系列的替換語句
    string = string.replace("--", "-")
    string = string.replace("-+", "-")
    string = string.replace("++", "+")
    string = string.replace("*+", "*")
    string = string.replace("/+", "/")
    string = string.replace(" ", "-")

    return string


# 檢查函數(檢查輸入的表達式是否合法)
def chek_expression(string):
    check_result = True   # 標志位

    if not string.count("(") == string.count(")"):   # 檢查括號是否完整
        print("輸入錯誤,未匹配到完整括號!")
        check_result = False

    if re.findall('[a-pr-z]+', string.lower()):   # 檢查是否包含字母
        print("輸入錯誤,包含非法字符!")
        check_result = False

    return check_result


# 加減法函數
def add_minus(string):

    add_regular = r'[\-]?\d+\.?\d*\+[\-]?\d+\.?\d*'       # 定義一個匹配的規則
    sub_regular = r'[\-]?\d+\.?\d*\-[\-]?\d+\.?\d*'       # 同上
# 注解:[\-]? 如果有負號,匹配負號; \d+ 匹配最少一個數字; \.? 是否有小數點,有就匹配;\d* 是否有數字有就匹配
# \+ 匹配一個加號;  [\-]?\d+\.?\d*  這幾個同上

    # 加法
    while re.findall(add_regular, string):    # 按照regular規則獲取一個表達式,用while循環,把所有加法都算完

        add_list = re.findall(add_regular, string)
        for add_stars in add_list:
            x, y = add_stars.split('+')      # 獲取兩個做加法的數(以+號作為分割對象),分別賦給x和y
            add_result = '+' + str(float(x) + float(y))
            string = string.replace(add_stars, add_result)   # 替換
        string = format_string(string)

    # 減法
    while re.findall(sub_regular, string):    # 用while循環,把所有減法都算完

        sub_list = re.findall(sub_regular, string)
        for sub_stars in sub_list:
            x, y = sub_stars.split('-')  # 獲取兩個做減法的數(以-號作為分割對象),分別賦給x和y
            sub_result = '+' + str(float(x) + float(y))
            string = string.replace(sub_stars, sub_result)   # 替換
        string = format_string(string)

    return string


# 乘、除法函數
def multiply_divide(string):
    regular = r'[\-]?\d+\.?\d*[*/][\-]?\d+\.?\d*'  # 定義一個匹配的規則regular

    while re.findall(regular, string):
        expression = re.search(regular, string).group()    # 按照regular規則獲取一個表達式

        # 如果是乘法
        if expression.count('*') == 1:
            x, y = expression.spilt('*')
            mul_result = str(float(x) * float(y))
            string = string.replace(expression, mul_result)  # 計算結果替換原表達式
            string = format_string(string)  # 格式化

        # 如果是除法
        if expression.count('/') == 1:
            x, y = expression.spilt('/')
            div_result = str(float(x) / float(y))
            string = string.replace(expression, div_result)
            string = format_string(string)  # 格式化

        # 如果是階乘
        if expression.count('**') == 1:
            x, y = expression.spilt('**')
            pow_result = 1
            for i in range(int(y)):
                pow_result *= int(x)
            string = string.replace(expression, str(pow_result))
            string = format_string(string)  # 格式化

    return string


# 主程序
while True:
    source = input("請輸入表達式:")   # 輸入要計算的式子

    if source == "Q":    # 該判斷語句只能寫在前面,寫后面會報錯
        exit()   # 如果輸入是Q,退出

    elif chek_expression(source):
        print("eval result: ", eval(source))   # eval() 是把其他類型轉換為字符串
        sourse = format_string(source)

        if source.count("(") > 0:
            stars = re.search(r'\([^()]*\)', source).group()   # 去括號,得到括號里的字符串
            replace_stars = multiply_divide(stars)   # 將括號的表達式進行乘除運算
            replace_stars = add_minus(stars)         # 將乘除的結果進行加減運算
            source = format_string(source.replace(stars, replace_stars))  # 用計算結果替換括號字符串

        # 沒有括號直接進行運算
        else:
            replace_stars = multiply_divide(source)   # 乘除運算
            replace_stars = add_minus(source)    # 加減運算
            source = source.replace(source, replace_stars)


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM