Thursday, December 3, 2015

Why is Python a high level language?

High level languages are usually defined as languages in which one instruction translates to more than one machine level instructions. Though I find this definition simple and precise, I also find that a lot of students find it difficult to understand this definition.

A simple demonstration can be done in Python. First one must understand that any hardware comes with it's own instruction set. The hardware allows others to instruct it using an instruction set which is created by the manufacturer of the hardware. This is the basic instruction set and consists of things like ADD, SUB, LOAD, BIND etc.

In Python we may consider a hypothetical hardware which needs instructions called byte code to run. Now we see how a simple python program converts to multiple byte code instructions per statement.

First let us create a simple function in Python.
def my_function():
    x = 1
    y = 2
    z = x + y
What this does is create a function that creates two variables x and y and adds them together before storing them in another variable called z.

To see the machine level instructions which must be carried out to complete this function we will add the following to the python file (possibly myfn.py)

import diss
diss.diss(my_function)

What we get as output is:

  2           0 LOAD_CONST               1 (1)
              3 STORE_FAST               0 (x)

  3           6 LOAD_CONST               2 (2)
              9 STORE_FAST               1 (y)

  4          12 LOAD_FAST                0 (x)
             15 LOAD_FAST                1 (y)
             18 BINARY_ADD
             19 STORE_FAST               2 (z)
             22 LOAD_CONST               0 (None)
             25 RETURN_VALUE


The initial numbers in the first column are line numbers in myfn.py

Hence we can see the expected machine instructions to compute this function. Note that line 2 and 3 in our file expanded to 2 statements while line 4 to 6.

Hence we conclude that Python is a high level language.
For more details refer to the Python docs.

No comments:

Post a Comment