Monday, 18 May 2020

This week 2/2020 - Python

I had always aversion to Python but finally I forced myself to try it. I am developing myself in machine learning area and most examples and algorithm sources are in Python - life forced me.

In this post in a nut shell I describe basic and most important topic of language like:
- why it was created?
- who use it and why?
- a very short characteristic of language and biggest differences which I noticed.

Python was created 1985 by Guido van Rossun as an interpreted, interactive, object-oriented high level language. Name of language is after Monty Python's Flying Circus TV comedy series. It was designed to be readable and easy to run in academic environment. It uses dynamic data typing validated in runtime. It supports functional programming and it is possible to compile Python code into bytecode usually in bigger applications.
It is good to add that till this year (2020) there were two major versions: 2.x and 3.x. Since 2008 when version 3 was introduced, the older version has been still developed. Versions are incompatible to themselves, so when you learn Python focus on which version you use.
When I write this post current version is 3.8.3 but I trained on 3.6.9 and I used only a few features of the language.

Creator cared of interactive console so each command can be added add-hoc and executed. Probably that's why this language won in scientific community, where code doesn't need to be compiled to be executed.
Currently in Python we can find a lot of tools and libraries to load data, process it and present it (plotters, etc.). Dynamic data type definition is useful when we experiment with code but from my point of view can be dangerous during runtime, when we can meet type incompatibility in runtime.

How Python stand out from the rest languages? The first difference is that Python required some code layout. It doesn't use semicolons and braces so it requires lines and indentations. This is what doesn't convince me to Python. Of course I like pretty formatted code but I acclimated to braces and I don't belief that we can live without them.

1
2
3
4
if filename and os.path.isfile(filename):
    with open(filename) as fobj:
        startup_file = fobj.read()
    exec(startup_file)

Other differences that language uses words "not", "and" and "or" in conditional statements.
Python widely support list. Programmer can add lists, multiply elements, search and simply filter it by two or there additional signs.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
print([1, 2, 3] + [4, 5, 6])  # [1, 2, 3, 4, 5, 6]
print(['blog'] * 4)  # ['blog', 'blog', 'blog', 'blog']
print(3 in [1, 2, 3])  # True
for x in [1, 2, 3, 4]:  # 1 2 3 4
    print(x, end=' ')
print("")
L = ['one', 'two', 'there', 'four']
print(L[1])  # there
print(L[-1])  # four
print(L[2:])  # ['there', 'four']
print(L[:2])  # ['one', 'two']

Python includes tuples which support similar operations as for list and dictionary type as well.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
# Tuple
tuple1 = ('cat', 'dog', 19, 200)
tuple2 = "a", 4, "c", 2.3

print("tup1[0]: ", tuple1[1])  # tup1[0]:  dog
print("tup2[1:4]: ", tuple2[1:4])  # tup2[1:4]:  (4, 'c', 2.3)

# Dictionary type
dict = {'Name': 'Tom', 'Age': 27, 'eyes': 'blue'}
print("dict['Name']: ", dict['Name'])  # dict['Name']:  Tom
print("dict['Age']: ", dict['Age'])  # dict['Age']:  27



Python allows to inheritance, overriding but I didn't find possibility to overloading methods.


 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
class Parent:  # define parent class
    parentAttr = 100

    def __init__(self):
        print("Calling parent constructor")

    def parentMethod(self):
        print('Calling parent method')

    def setAttr(self, attr):
        print('setAttr(self,attr)')
        Parent.parentAttr = attr

    def getAttr(self):
        print('setAttr(self)')
        print("Parent attribute :", Parent.parentAttr)


class Child(Parent):  # define child class - inheritance
    def __init__(self):
        print("Calling child constructor")

    def parentMethod(self):  # method overriding
        print('Calling parent method in child')

    def childMethod(self):
        print('Calling child method')


Python contains annotations mechanism:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
def decorator(annotatedText):  # definition of annotation
    def text_generator(old_function):
        def new_function(*args, **kwds):
            return annotatedText + ' ' + old_function(*args, **kwds)
        return new_function
    return text_generator # it returns the new generator

# Usage
@decorator('prefix') # text attached before function resul
def return_text(text):
    return text

# Now return_text is decorated and reassigned into itself
print(return_text('myText')) # 'prefix myText'


and finally lambda expressions:

1
2
d = lambda d : d + 20
print(d(10)) # 30

My feeling a bit changed after I went through a tutorial and wrote some code but it is too little to feel free in it. Maybe after more machine learning exercises I will love it.

Resources:
1. Python 3 Tutorial (tutorialspoint)
2. Python documentation
3. How to Use Python Lambda Functions

No comments:

Post a Comment