eval() Evaluate expression
Last updated: 2026-09-22
eval() Evaluate expression
eval() evaluates a Python expression string and returns the result. **Security warning**: never eval untrusted input.
| Category | Built-in Functions |
|---|---|
| Kind | Built-in Function |
| Python Version | all |
📝 Syntax
eval(expression[, globals[, locals]])
⚙️ Parameters
| expression Required | A Python expression string or code object. |
|---|---|
| globals Optional | The global namespace dict.(Default:None) |
| locals Optional | The local namespace dict.(Default:None) |
Returns:The result of evaluating the expression.
💥 Raises
SyntaxError— Raised when the expression has a syntax error.NameError— Raised when the expression references an undefined name.TypeError— Raised when globals or locals is not a dict.
▶ Example
Edit the code, press Run, and see the result in the output panel:
Output:
15
1024
⚠️ Warning eval can execute arbitrary code; use ast.literal_eval in production.
🏷️ Related Built-in Functions
💡 Related Cases
More case studies coming soon — check back later.
❓ FAQ
QWhat is the difference between eval() and exec()?
Aeval() executes a single expression and returns its result (e.g. eval('1 + 2') returns 3); exec() executes statements or code blocks (if, for, def, etc.) and returns None.
QWhat happens with eval('x = 1')?
AIt raises a SyntaxError. An assignment is a statement, not an expression, and eval() only evaluates expressions; use exec() to run statements.
QWhy should I not eval user input?
Aeval() can execute arbitrary code, such as the string eval("__import__('os').system('dir')"); to parse user input use ast.literal_eval, which only handles literals.
QCan eval use variables defined outside?
ABy default yes (it uses the current global/local namespace); you can also pass custom namespaces via the globals/locals arguments to restrict which names an expression can access.