Home > Backend Development > Python Tutorial > Python program for calculating arithmetic operations from strings

Python program for calculating arithmetic operations from strings

王林
Release: 2023-08-19 13:21:19
forward
2022 people have browsed it

Python program for calculating arithmetic operations from strings

Arithmetic operations are mathematical calculations performed on numeric data types. The following are the arithmetic operations allowed by Python.

  • Addition ( )

  • Subtraction (-)

  • Multiplication (*)

  • Division (/)

  • Floor Division (//)

  • Modulo (%)

  • Exponential operation (**)

There are several ways to perform arithmetic operations from strings. Let’s look at them one by one.

Use eval() function

In Python, the eval() function evaluates an expression passed as a string and returns the result. We can use this function to calculate arithmetic operations in strings.

The Chinese translation of

Example

is:

Example

In this method, eval() The function evaluates the expression "2 3 * 4 - 6 / 2" and returns the result, which is then stored in the variable "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)
Copy after login

Output

The result of the given expression: 11.0
Copy after login

Implementing arithmetic parsing and evaluation

If we wish to have more control over the parsing and evaluation process, we can implement our own arithmetic parsing and evaluation logic. This approach involves splitting a string expression into individual operands and operators, parsing them, and performing arithmetic operations accordingly.

The Chinese translation of

Example

is:

Example

In this example, the expression is split into individual tokens using the split() method. These tokens are then parsed and evaluated one by one based on the arithmetic operators specified in the operator dictionary. The result is calculated by applying the appropriate operator to the accumulated result and the current operand.

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)
Copy after login

Output

The result of given expression 7.0
Copy after login

Use operator module

In Python, we have the operator module, which provides functions corresponding to the built-in Python operators. We can use these functions to perform arithmetic operations based on operators in string expressions.

The Chinese translation of

Example

is:

Example

In this example, we define a dictionary that maps operators to their corresponding functions in the operator module. We split the expression into tokens where operators and operands are separated. We then iterate over these tokens, applying the corresponding operator function to the result and next operand.

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)
Copy after login

Output

The arithmetic operation of the given expression: 20
Copy after login

The above is the detailed content of Python program for calculating arithmetic operations from strings. For more information, please follow other related articles on the PHP Chinese website!

source:tutorialspoint.com
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template