從字串計算算術運算的Python程式


算術運算是在數值資料型別上進行的數學計算。以下是Python中允許的算術運算。

  • 加法 (+)

  • 減法 (-)

  • 乘法 (*)

  • 除法 (/)

  • 地板除 (//)

  • 取模 (%)

  • 冪運算 (**)

有幾種方法可以從字串計算算術運算。讓我們一一來看。

使用eval()函式

Python中的eval()函式計算作為字串傳遞的表示式並返回結果。我們可以使用此函式從字串計算算術運算。

示例

在這種方法中,eval()函式計算表示式“2 + 3 * 4 - 6 / 2”並返回結果,然後將其儲存在變數“result”中。

def compute_operation(expression):
   result = eval(expression)
   return result
expression = "2 + 3 * 4 - 6 / 2"
result = compute_operation(expression)
print("The result of the given expression:",result)

輸出

The result of the given expression: 11.0

實現算術解析和評估

如果我們想要更多地控制解析和評估過程,我們可以實現我們自己的算術解析和評估邏輯。這種方法包括使用split()方法將字串表示式拆分為單個運算元和運算子,解析它們,並相應地執行算術運算。

示例

在這個例子中,表示式使用split()方法被拆分成單個標記。然後根據operators字典中指定的算術運算子迭代地解析和評估標記。結果是透過將適當的運算子應用於累積結果和當前運算元來計算的。

def compute_operation(expression):
   operators = {'+': lambda x, y: x + y,
                  '-': lambda x, y: x - y,
                  '*': lambda x, y: x * y,
                  '/': lambda x, y: x / y}
   tokens = expression.split()
   result = float(tokens[0])
   for i in range(1, len(tokens), 2):
      operator = tokens[i]
      operand = float(tokens[i+1])
      result = operators[operator](result, operand)
   return result
expression = "2 + 3 * 4 - 6 / 2"
result = compute_operation(expression)
print("The result of given expression",result)

輸出

The result of given expression 7.0

使用operator模組

在Python中,我們有operator模組,它提供了與內建Python運算子對應的函式。我們可以使用這些函式根據字串表示式中存在的運算子執行算術運算。

示例

在這個例子中,我們定義了一個字典,它將運算子對映到operator模組中相應的函式。我們將表示式拆分成標記,其中運算子和運算元是分開的。然後,我們遍歷這些標記,將相應的運算子函式應用於結果和下一個運算元。

import operator
expression = "2 + 3 * 4"
ops = {
   '+': operator.add,
   '-': operator.sub,
   '*': operator.mul,
   '/': operator.truediv,
}
tokens = expression.split()
result = int(tokens[0])
for i in range(1, len(tokens), 2):
   operator_func = ops[tokens[i]]
   operand = int(tokens[i + 1])
   result = operator_func(result, operand)
print("The arithmetic operation of the given expression:",result)

輸出

The arithmetic operation of the given expression: 20

更新於:2023年8月2日

335 次瀏覽

開啟您的職業生涯

完成課程獲得認證

開始學習
廣告
© . All rights reserved.