- Trending Categories
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
Physics
Chemistry
Biology
Mathematics
English
Economics
Psychology
Social Studies
Fashion Studies
Legal Studies
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Execute a String of Code in Python
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.
Advertisements