In this tutorial, we will delve into one of Python’s built-in functions, the exec()
function. This function is a powerful tool that allows you to dynamically execute Python program which is either a string or object code.
Basic Usage of exec()
The basic syntax for the exec()
function is as follows:
exec(object, globals, locals)
The parameters are:
- object: Required. Either a string or an object code. If it is a string, the string is parsed as a suite of Python statements which is then executed.
- globals: Optional. A dictionary containing global methods and variables.
- locals: Optional. A dictionary containing local methods and variables.
A Simple Example of exec()
program = 'a = 5\nb=10\nprint("Sum =", a+b)'
exec(program)
In this example, we have defined a multi-line program as a string and passed it to exec()
. The output will be “Sum = 15”.
Dynamically Executing Code with exec()
You can also use exec()
to execute dynamic expressions that you create on-the-fly during runtime. Here’s an example:
expression = input("Enter an expression:")
exec(expression)
This script prompts the user to enter any valid python expression which then gets executed by the exec().
Using exec() with globals and locals
The exec()
function also accepts optional global and local parameters. These are dictionaries that define the global and local symbol table respectively. If provided, exec()
executes the code within these namespaces.
global_var = 1
def test_exec():
local_var = 10
exec('print(global_var); print(local_var)', {'global_var': 2}, {'local_var': 20})
test_exec()
In this example, we have defined a global variable ‘global_var’ and a local variable ‘local_var’. We then execute a string of Python code that prints both variables. However, we provide different values for these variables in the globals and locals dictionaries passed to exec(). The output will be “2” and “20”, not “1” and “10”.
Conclusion
The Python exec()
function is a powerful tool that allows you to dynamically create Python code during runtime. However, it should be used sparingly as it can make your code harder to debug if overused or misused.
We hope this tutorial has helped you understand how to use the Python exec() function effectively!