Python: exec() function
exec() function
The exec() function is used to execute the specified Python code. object must be either a string or a code object.
Version:
(Python 3)
Syntax:
exec(object[, globals[, locals]])
Parameter:
Name | Description | Required / Optional |
---|---|---|
object | Either a string or a code object. | Required |
globals | A dictionary containing global parameters. | Optional |
locals | A dictionary containing local parameters. | Optional |
Example-1: Python exec() function
x = 5
print(exec('x'))
Output:
None
Example-2: Python exec() function
Example = 'x = 6\ny=15\nprint("Sum =", x+y)'
exec(Example)
Output:
Sum = 21
Pictorial Presentation:
Python Code Editor:
Previous: eval()
Next: filter()
Test your Python skills with w3resource's quiz
- Weekly Trends and Language Statistics
- Weekly Trends and Language Statistics