Python exec() Method – [With Examples]

In this tutorial we will learn about python exec() method and its uses with examples.

Python exec() method

The exec() is a built-in python Method that executes the specified python code dynamically. Can be a string or a code object.

Python exec() syntax :

exec(object, globals, locals)

Python exec() Parameters

exec() takes three parameters as argument:

  • object –  A string or code object.
  • globals (optional) – A dictionary containing global parameters.
  • locals (optional) –  A dictionary containing local parameters.

Lets see an example of python exec() function.

Example 1: How to use exec() in python?

code = ‘print(“Hello Python”)’


Hello Python

Example 2 : exec() function with user input function.

code = ‘a = int(input(“Enter a Number: “))\nprint(a)’


Enter a Number: 25