w3resource

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: Built-in-function - exec() function

Python Code Editor:

Previous: eval()
Next: filter()

Test your Python skills with w3resource's quiz



Python: Tips of the Day

How do I check if a list is empty?

For example, if passed the following:

a = []
if not a:
  print("List is empty")

Ref: https://bit.ly/2A4JXx9