Python exec Function with Examples - Python Tutorial | Logic Practice
Python Course / Other / Python exec Function with Examples

Python exec Function with Examples

BLUF: This lesson on Python exec Function with Examples provides a comprehensive guide to understanding and implementing this concept in Python. Whether you're a beginner or looking to refresh your knowledge, you'll find clear explanations and interactive code examples here.
Key Concept: Python exec Function with Examples

Mastering Python exec Function with Examples is essential for building efficient Python applications. Focus on the syntax and the best practices highlighted in this tutorial.

The exec function in Python facilitates the dynamic execution of Python code, which can be provided as either a string or object code. It is capable of handling extensive blocks of code, in contrast to the eval function, which is limited to processing a single expression.

Python exec Function Syntax

It has the following syntax:

Example

exec(object, globals, locals)

Parameters

  • object: It should be either string or code object.
  • globals (optional): It is used to specify global functions.
  • locals (optional): It is used to specify local functions.
  • Different Examples for Python exec function

Here are several instances of the exec function, as illustrated below:

Python exec Function Example 1

This example shows working of exec function.

Example

x = 5

exec('print(x==5)')

exec('print(x+4)')

Output:

Output

True

9

Python exec Function Example 2

This example shows exec dynamic code execution

Example

from math import *

for l in range(1, 3):

    func = input("Enter Code Snippet to execute:\n")

    try:

        exec(func)

      except Exception as ex:

        print(ex)

        break

print('Done')

Output:

Output

Enter Code Snippet to execute:

print(sqrt(16))

4.0

Enter Code Snippet to execute:

print(min(2,1))

1

Done

Input Required

This code uses input(). Please provide values below:

Logic Practice
Install Logic Practice
Add to home screen for a faster app-like experience