Evaluating Expressions using Python’s eval()

Evaluate Mathematical Expressions in Python

Evaluating a mathematical expression using the value of the variable x.

Python3




expression = 'x*(x+1)*(x+2)'
print(expression)
 
x = 3
 
result = eval(expression)
print(result)


Output:

x*(x+1)*(x+2)
60

Evaluate Boolean Expressions in Python

Here the eval statement x == 4 will evaluate to False because the value of x is 5, which is not equal to 4. In the second eval statement, x is None will evaluate to True because the value of x is None, and is None checks for object identity, not value equality.

Python3




x = 5
print(eval('x == 4'))
 
x = None
print(eval('x is None'))


Output:

False
True

Evaluate Conditional Expressions in Python

We can also evaluate condition checking on the Python eval() function.

Python3




# check if element in tuple
chars = ('a', 'b', 'c')
print("'d' in chars tuple?", eval("'d' in chars"))
 
# check if number is greater or lesser
num = 100
print(num, "> 50?", eval('num > 50'))
 
# checking if number is even
num = 20
print(num, "is even?", eval('num % 2 == 0'))


Output:

'd' in chars tuple? False
100 > 50? True
20 is even? True

eval in Python

Python eval() function parse the expression argument and evaluate it as a Python expression and runs Python expression (code) within the program.

Similar Reads

Python eval() Function Syntax

Syntax: eval(expression, globals=None, locals=None) Parameters: expression: String is parsed and evaluated as a Python expression globals [optional]: Dictionary to specify the available global methods and variables. locals [optional]: Another dictionary to specify the available local methods and variables. Return: Returns output of the expression....

eval() Function in Python Example

Python3 print(eval('1+2')) print(eval("sum([1, 2, 3, 4])"))...

Evaluating Expressions using Python’s eval()

...

Vulnerability issues with Python eval() Function

...

Making eval() safe

Evaluate Mathematical Expressions in Python...