The difference between exec and eval in Python

Source: Internet
Author: User

Exec can execute dynamic Python code, like the Eval function of JavaScript;

The eval function in Python calculates the Python expression and returns the result;

(Exec does not return results, print (eval ("...") prints none);

For example:

exec ("print (\" Hello, world\ ")") Hello, World exec ("a = 2")>>> a2

There is a scope (namespace, scope) concept, in order to not break the current scope, you can create a new scope (a dictionary) exec (JavaScript does not have this feature):

>>> scope = {}exec("a = 4", scope)>>> A 2>>> scope['a']4>>> scope.keys () Dict_keys ([  'a'__builtins__'])

__builtins__ contains all of the built-in functions and values

The difference between exec and eval in Python

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.