Execute a String of Code in Python

PythonServer Side ProgrammingProgramming

There are times when you need the entire block of code as a string and want this code to execute as part of a bigger python program. IN this article we will see how we can pass code as a string to a variable and then use that variable in a wrapper program which will then execute this program as a python code.

The exec() function is used to execute the code. The code has to be embedded within three “.

Example

code = """
numbers = [11,33,55,39,55,75,37,21,23,41,13]
for num in numbers:
   if num%2 == 0:
      print ('the list contains an even number')
      break
else:
   print ('the list doesnot contain even number')
"""
exec(code)

Output

Running the above code gives us the following result −

the list does not contain even number.
raja
Updated on 23-Aug-2019 12:20:36

Advertisements