How to Use the Python eval() Function

09/18/2021

Contents

In this article, you will learn how to use the Python eval() function.

Python eval() Function

The Python eval() function is a built-in function that evaluates a string as a Python expression and returns the result. Here’s how you can use it:

Syntax
eval(expression, globals=None, locals=None)
Parameters
  • expression: The string containing the Python expression you want to evaluate.
  • globals (optional): A dictionary containing the global variables in the current scope. If not provided, the globals from the calling scope are used.
  • locals (optional): A dictionary containing the local variables in the current scope. If not provided, the locals from the calling scope are used.
Example
x = 10
y = 5

result = eval('x + y')
print(result)  # Output: 15

result = eval('x * y')
print(result)  # Output: 50

In the above example, we defined two variables x and y and then used the eval() function to evaluate the expressions x + y and x * y.

It is important to note that the eval() function can execute any valid Python code, including potentially dangerous or malicious code. Therefore, it should only be used with trusted inputs, or in situations where the input is carefully validated and sanitized. Using eval() with untrusted inputs can lead to security vulnerabilities.