One most common question about python is that it is a compiled language or interpreted language or both?
First, see what is terms compiled and interpreted means(in a simple world):
Compiled Language: The high-level Language whose code first converted into machine code by the compiler and then executed by the executor.
Interpreted Language: The high-level language whose code executed by an interpreter on the go.
In various books on python programming, it is mention that Python is an Interpreted Language. And, also as per the above definitions Python is an Interpreted language.
But the world is not as simpler and limited. So that is half correct that Python is an Interpreted language. The Python program first compiled and then interpreted. This compilation part is hidden from programmers, so they think that it is an interpreted language. The compilation part is done when we execute our code and this will generate byte-code and internally this byte-code gets converted by python virtual machine according to the machine and operating system.
now if we run this code using the command prompt or terminal, first save this file using
and run the following command :
python -m py_compile main.py
As we press enter the compiled code will get generated and saved in a folder which is created inside the folder contain our python code.
There is one another way to compile python code by using
compile() method. This function takes a string, byte-string, or AST as input and returns a python code object which is executed by using
eval() method or
compile(source, filename, mode, flags=0, dont_inherit=False, optimize=-1)
- Source : String, byte-string, AST object
- Filename : Filename from which code was read
- mode : three mode 'exec', 'eval', and 'single'
- Flags(optional) and dont_inherit(optional) – Default value=0. It takes care that which future statements affect the compilation of the source.
- Optimize(optional) – It tells optimization level of compiler. Default value -1.
srcCode = 'x = 10\ny = 20\nmul = x * y\nprint("mul =", mul)' execCode = compile(srcCode, 'mulstring', 'exec') exec(execCode)
mul = 200
Thanks for reading.