How to Use compile() Function in PythonPython Basics


The compile() function compiles a string into byte code.

Example

#!/usr/bin/python3
# -*- coding: UTF-8 -*-

str1 = "for i in range(0,5): print(i)"
a = compile(str1,'','exec')
exec(a)

Output:

0
1
2
3
4

Syntax

compile(source, filename, mode[, flags[, dont_inherit]])

Parameters

Name Description
source String
filename The name of the file where the source comes.
mode Specify the type of compiled code.
flags How to compile the source. The default is 0.
dont_inherit How to compile the source. The default is False.

Return Value

It returns byte code of a string.

© 2024 Learnwithgpt.org, all rights reserved. Privacy Policy | Contact Us