Post

Python exec() Method

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 function that executes the specified python code dynamically. Can be a string or a code object.

Python exec() syntax :

1
2
exec(object, globals, locals)

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() function in python?

code = 'print("Hello Python")'

exec(code)

Output:

1
2
Hello Python 

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

1
2
3
4
code = 'a = int(input("Enter a Number: "))\nprint(a)'

exec(code)

Output:

1
2
3
Enter a Number: 25
25

This post is licensed under CC BY 4.0 by the author.