exec(): dynamically executes Python code

exec(object, global,local ) execute valid python code

object: input object of string or code object
global: (optional ) global dictionary object
local: (optional ) local dictionary object

Return : The return value is None.

Using string object

my_str="x='plus2net'\nprint(x)"
exec(my_str)
Output
plus2net

Using code object

We create a code object by using compile()
cb=compile('print("Hello")', '', 'single')
exec(cb)
Output
Hello

Using restrictions

We can allow some functions in global scope only to execute by using global option. Let us import our math module and find the sum of a iterable_object This will generate error as we have used one empty dictionary ( not allowing any method ) .
import math
str="print(math.fsum([1,2,3,4,5]))"
exec(str,{})
This will work as we have allowed math.fsum to execute. Output is 15.0
import math
str="print(fs([1,2,3,4,5]))"
exec(str,{"fs":math.fsum}) # 15.0 

builtin functions

exec() has full access to all builtin functions of Python. This code will not generate any error though we have supplied an empty dictionary ({}) to globals. Output is 15
str="print(sum([1,2,3,4,5]))"
exec(str,{})  # 15 

Difference Between eval() and exec() in Python

eval() is used to evaluate a single Python expression and return the result. It's suitable for simple evaluations of Python expressions that have a return value.

exec() is used for executing dynamically generated Python code which can be more complex than a single expression. It can execute multiple statements and even complex code structures, such as loops or function definitions, but it doesn't return the result.
All Built in Functions in Python dir() eval() compile()
Subhendu Mohapatra — author at plus2net
Subhendu Mohapatra

Author

🎥 Join me live on YouTube

Passionate about coding and teaching, I publish practical tutorials on PHP, Python, JavaScript, SQL, and web development. My goal is to make learning simple, engaging, and project‑oriented with real examples and source code.



Subscribe to our YouTube Channel here



plus2net.com







Python Video Tutorials
Python SQLite Video Tutorials
Python MySQL Video Tutorials
Python Tkinter Video Tutorials
We use cookies to improve your browsing experience. . Learn more
HTML MySQL PHP JavaScript ASP Photoshop Articles Contact us
©2000-2025   plus2net.com   All rights reserved worldwide Privacy Policy Disclaimer