Python eval() Function – Evaluate Expressions from Strings

Python eval() Function

The eval() function in Python takes a string and evaluates it as a Python expression. It can be used to run dynamic Python code that's stored as a string.

Syntax

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

Parameters:

  • expression – A string that contains a valid Python expression.
  • globals (optional) – A dictionary to define the global namespace.
  • locals (optional) – A dictionary to define the local namespace.

Returns:

  • The result of evaluating the expression (could be a number, string, list, etc.).

Example 1: Evaluate a Mathematical Expression

result = eval("5 + 10 * 2")
print(result)
25

Example 2: Use Variables in eval()

x = 3
y = 4
expression = "x * y + 2"
print(eval(expression))
14

Example 3: Using globals and locals

code = "a + b"
print(eval(code, {"a": 5, "b": 10}))
15

Use Case: When to Use eval()

  • Useful in calculators, config parsers, or dynamic logic evaluators.
  • Can execute user-defined expressions at runtime.

Warning: Security Risk

Never use eval() on untrusted input! It can execute arbitrary code, leading to serious security issues.

Example of dangerous input:

eval("__import__('os').system('rm -rf /')")

Instead, use ast.literal_eval() if you just want to safely evaluate basic data types.

Common Mistakes

  • Invalid syntax inside the string will raise a SyntaxError.
  • Runtime errors like division by zero can still occur inside eval.

Interview Tip

While eval() isn’t commonly used in interviews, understanding it shows that you know Python’s dynamic features and their risks.

Summary

  • eval() evaluates a string as a Python expression.
  • It can return different data types based on the expression.
  • Use it with caution — it can be unsafe with user inputs.

Practice Problem

Ask the user to enter a math expression (like 2 + 3 * 4) and print the result using eval():

expr = input("Enter a math expression: ")
print("Result:", eval(expr))