Python程序用于从字符串中计算算术操作

python程序用于从字符串中计算算术操作

算术运算是对数值数据类型进行的数学计算。以下是Python允许的算术运算。

加法 (+)

减法 (-)

乘法 (*)

立即学习“Python免费学习笔记(深入)”;

Division (/)

地板除法 (//)

Modulo (%)

指数运算 (**)

有几种方法可以从字符串中计算算术运算。让我们逐个来看。

使用eval()函数

在Python中,eval()函数会评估作为字符串传递的表达式,并返回结果。我们可以使用这个函数来计算字符串中的算术操作。

Example

的中文翻译为:

示例

在这种方法中,eval() 函数评估表达式”2 + 3 * 4 – 6 / 2″并返回结果,然后将结果存储在变量”result”中。

def compute_operation(expression):   result = eval(expression)   return resultexpression = "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

登录后复制

实现算术解析和评估

如果我们希望对解析和评估过程有更多的控制,我们可以实现自己的算术解析和评估逻辑。这种方法涉及将字符串表达式分割为单个操作数和运算符,对它们进行解析,并相应地执行算术运算。

Example

的中文翻译为:

示例

在这个例子中,表达式使用split()方法被分割成单个的标记。然后,根据操作符字典中指定的算术运算符,逐个解析和评估这些标记。通过将适当的操作符应用于累积的结果和当前操作数,计算出结果。

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 resultexpression = "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运算符对应的函数。我们可以使用这些函数根据字符串表达式中的运算符执行算术运算。

Example

的中文翻译为:

示例

在这个例子中,我们定义了一个字典,将操作符映射到它们在operator模块中对应的函数。我们将表达式分割成标记,其中操作符和操作数被分开。然后,我们遍历这些标记,将对应的操作符函数应用于结果和下一个操作数。

import operatorexpression = "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

登录后复制

以上就是Python程序用于从字符串中计算算术操作的详细内容,更多请关注【创想鸟】其它相关文章!

版权声明:本文内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容, 请发送邮件至253000106@qq.com举报,一经查实,本站将立刻删除。

发布者:PHP中文网,转转请注明出处:https://www.chuangxiangniao.com/p/2227324.html

(0)
上一篇 2025年2月26日 12:20:35
下一篇 2025年2月20日 02:31:45

AD推荐 黄金广告位招租... 更多推荐

相关推荐

发表回复

登录后才能评论