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.

CategoryBuilt-in Functions
KindBuilt-in Function
Python Versionall

📝 Syntax

eval(expression[, globals[, locals]])

⚙️ Parameters

expression RequiredA Python expression string or code object.
globals OptionalThe global namespace dict.(Default:None)
locals OptionalThe local namespace dict.(Default:None)

Returns:The result of evaluating the expression.

💥 Raises

▶ 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.
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.
Web-Tutorial.com

Web-Tutorial Tech Team

A team of developers maintaining programming tutorials. Each tutorial is written and reviewed by developers with expertise in that field. We work to keep our content accurate and reliable — if you spot an issue, please let us know.

100%

🙏 帮我们做得更好

我们是刚上线的编程教程站,几个人的小团队,精力有限。页面虽经检查,难免还有疏漏——链接失效、排版错乱、内容有误、语言生硬……

如果您发现了,麻烦告诉我们,我们会在收到反馈后第一时间进行修复,再次感谢您的光临 🙏