How to evaluate mathematical expressions in Python

Share

A mathematical expression is a statement with at least two different numbers (known or unknown) and at least one operation.

What a statement lacks may be the most crucial component in defining it. The equals symbol does not appear in mathematical expressions (or a less than, greater than, or similar relation).

Understanding these components is essential to learning how to create a mathematical expression. A mathematical expression typically consists of two parts: terms (Constant terms, Variables, Coefficients) and operations (addition, subtraction, multiplication, division, exponents, roots).

For this answer, we will use the Python eval() function to evaluate mathematical expressions in Python.

Python eval()function

The eval() function runs a Python expression (code) within the program after parsing the expression supplied.

Syntax

The syntax of eval() is:

eval(expression, globals=None, locals=None)

Parameters

The eval() function requires these three inputs:

  • Expression: the string that has been processed and evaluated as a Python expression.

  • Locals: an object of mapping; it is optional.

  • Globals: it is a dictionary, but it is also optional.

Example

#We will declare a variable num
num = 5
# Let's use the eval function to perform multiplication
x = 2
num_mul = eval("x * 2")
num_sq = eval('num * num')
num_add = eval("sum([3, 2, 5])")
num_addition = eval("50 + 20")
#printng the results
print(num_mul)
print(num_sq)
print(num_add)
print(num_addition)
  • Line 2: Define the variable num with value 5.

  • Line 5: Define the variable x with value 2.

  • Line 6: We use the eval() function to perform the multiplication of variable x and 2.

  • Line 7: Using the eval(), we multiplied the variable num with itself.

  • Line 8: We added three variables together using the sum() function inside the eval() function.

  • Line 9: Addition of two numbers with the eval() function.

Global variables

All names in our current global scope or namespace are referred to as global names. They are accessible from any location in our code.

At the moment of execution, eval() will have access to all the names supplied to globals in the dictionary. Consider the following example.

x = 10 # A global variable
y = 20 # A global variable
print(eval("x + y"))
  • Line 1: Global variable x is declared.

  • Line 2: Global variable y is declared.

  • Line 3: We printed the addition of the two globals using eval().

Local variables

Additionally, Python's eval() accepts locals as the third input. This additional optional parameter holds a dictionary. Local names are any names (variables, functions, etc.) defined within a specific function. Local names are only accessible within the enclosing function.

#define a local variable in the eval() function
print(eval("x + 2", {"x": 2}))
  • Line 1: We created a local variable inside the eval() function and added it to 2. Then inside the same function, we assigned value 2 to a variable.

Using eval() with strings

With the aid of the eval() function, we can perform the mathematical operation from a string-based input.

# initiale string
text = "4 * 6 - 3"
#lets print the original string
print("Original string is : " + text)
# Expression evaluation in String using eval()
result = eval(text)
print(result)
  • Line 2: A string variable that contains a mathematical expression.

  • Line 5: We print out the original text, which gives us a string character result.

  • Line 8: We use the eval function on the variable text, and we get a result showing the arithmetic result of its values.

Math expressions

We have already performed some math expressions such as addition, subtraction, and multiplication above.

Now let's try exponents and roots.

#we must import the math module
import math
print(eval("math.pi * 2"))
# Area of a circle
area = eval("math.pi * pow(10, 2)")
print(area)
#mixing the math expressions
print(eval("math.sqrt(math.pow(10,2))"))
  • Line 2: To use the math module we have to import it.

  • Line 4: We printed an operation on the mathematical pi (3.142) multiplied by 2.

  • Line 7: We calculated the area of a circle, using pi and exponent (pow).

  • Line 10: A mathematical expression showing the square root, and the exponent of a number in the eval() function.

Boolean

After evaluating a boolean expression (True or False), the Python interpreter returns a truth value. They are often used in if statements to assess if a condition is True or False.

a = 2 #define a global variable
b = 3 #define a global variable
#lets perform some operations
print(eval("a != b"))
print(eval("a > 1 and b > 2"))
print(eval("a is b"))
  • Line 1: Define a global variable a.

  • Line 2: Define a global variable b.

  • Line 5: Check to see if a is not equal to b.

  • Line 6: Check to see if a is greater than 1 and if b is greater than 2.

  • Line 7: Check to see if a is the same as b.

Conclusion

We can use Python's eval() function to evaluate Python expressions from a string- or code-based input. This built-in method might be helpful when attempting to evaluate Python expressions on the fly and trying to avoid the effort of constructing our own expressions evaluator from the start. Python's eval() presents security vulnerabilities since it is often manipulated. Restricting the use of the global and local dictionary can help to lower these hazards.

Copyright ©2024 Educative, Inc. All rights reserved