从字符串计算算术运算的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.