Exec and eval instances in Python-Python tutorial

Source: Internet
Author: User
This article mainly introduces the exec and eval usage examples in Python. This article summarizes the exec and eval functions in Python in a concise way and provides examples, if you need it, you can use exec to execute dynamic Python code, similar to Javascript's eval function. The eval function in Python can calculate the Python expression and return the result (exec does not return the result, print (eval ("... ") Print None );

The code is as follows:


>>> Exec ("print (\" hello, world \")")
Hello, world

>>> A = 1
>>> Exec ("a = 2 ")
>>>
2

There is a scope (namespace, scope) concept here. in order not to break the current scope, you can create a scope (a dictionary) to execute exec (Javascript does not have this function ):

The code is as follows:


>>> Scope = {}
>>> Exec ("a = 4", scope)
>>>
2
>>> Scope ['A']
4

>>> Scope. keys ()
Dict_keys (['A', '_ builtins _'])

_ Builtins _ contains all built-in functions and values;

The common {} does not contain _ builtins __

The code is as follows:


>>> A = {}
>>> A. keys ()
Dict_keys ([])

Like exec, eval can also use the namespace:

The code is as follows:


>>> Result = eval ('2 + 3 ')
>>> Result
5
>>> Scope = {}
>>> Scope ['A'] = 3
>>> Scope ['B'] = 4
>>> Result = eval ('a + B ', scope)
>>> Result
7

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.