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")'

exec(code)

Output:

Hello Python

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

code = 'a = int(input("Enter a Number: "))\nprint(a)'

exec(code)

Output:

Enter a Number: 25
25

 

Was this article helpful?
Share on: