Python – A short guide

In this article of Blog we will give a short revision to Python, a programming language very popular for data science applications. Our interest is particularly related to machine learning, where Python is very used as a consequence of the availability of a wide number of dedicated libraries.

So this article is preparatory for the implementation of machine learning algorithms that we will see in the following.

Python is an high level interpreted language. Python interpreter can be used to execute single line of code simply writing them after the >>> prompt (Fig.1) or a script using the python.exe command available in the installation directory followed by the name of the script (Fig.2).
Statement in a script are executed one at a time, starting from the first, in order from top to bottom. If a statement is a function call, the flow of execution goes to the first instruction of the body and when completes, the program come back to the calling point.

Fig.1 Python interpreter

Fig. 2 Python script execution

Assuming that you have basic programming knowledges, in the following we will see the basic sintax rules of Python programming language referring to version 3.

+, -, *, /, // floor division, % modulus, ** exponentiation

Logical Operators
and, or, not

Relational Operators

==, !=, >, <, >=, <=

Order of operations

Parentheses, exponentiation, multiplication and division, addiction and subtraction

String Operators

+ concatenation, * repetition


Begins with # symbol

Functions definition

def function_1(argument_1,argument_2):
return concat

The header of the function has to end with a colon, while the body has to be indented whit the same number of spaces (usually 4).

A pure function does not modify any of the objects passed to it as arguments and it has no effect other than returning a value.

Sometimes it is useful for a function to modify the objects it gets as parameters. In that case, the changes are visible to the caller. Functions that work this way are called modifiers.

Conditional execution

if int(x)>0:
print (“x is positive”)
elif int(x)==0:
print (“x is zero”)
print (“x negative”)

Keyboard input

x=input(“Write a number\n”)
The value returned from input() function is of string type.


while n > 0:
print (n)
n = n-1

for char in “String”:
print char

String manipulation

String slices
>>>s = ‘A long String’
>>>print (s[2:6])

String are immutable
>>> s = ‘A long string’
>>> s[8] = ‘S’
>>>TypeError: ‘str’ object does not support item assignment

String methods
>>> s1 = ‘string’
>>> s2 = s1.upper()
>>> print (s2)

In operator
>>> ‘s’ in ‘string’
>>> ‘b’ in ‘string’

String comparison
if s == ‘Green’:
print (‘Ok you can go’)
elif s < ‘Green’:
print (‘Your word,’ + s + ‘, comes before Green.’)

All the uppercase letters come before all the lowercase letters


A list is a sequence of values
>>>print (list[0])

>>>print (list)
[2, 2.0, [‘sublist1’, ‘sublist2’]]

Slide a list
for element in list:
    print (element)

for i in range(len(list)):
print (list[i])

List operations
>>> [1, 2, 3]+[4, 5, 6]
[1, 2, 3, 4, 5, 6]

>>> [1, 2, 3] * 3
>>>[1, 2, 3, 1, 2, 3, 1, 2, 3]

>>> t = [‘a’, ‘b’, ‘c’, ‘d’, ‘e’, ‘f’]
>>> t[1:3]
[‘b’, ‘c’]

>>> t[:4]
[‘a’, ‘b’, ‘c’, ‘d’]

>>> t[3:]
[‘d’, ‘e’, ‘f’]

List methods
>>> t = [‘a’, ‘b’, ‘c’]
>>> t.append(‘d’)
>>> print (t)
[‘a’, ‘b’, ‘c’, ‘d’]

>>> t1 = [‘a’, ‘b’, ‘c’]
>>> t2 = [‘d’, ‘e’]
>>> t1.extend(t2)
>>> print (t1)
[‘a’, ‘b’, ‘c’, ‘d’, ‘e’]

>>> t = [‘d’, ‘c’, ‘e’, ‘b’, ‘a’]
>>> t.sort()
>>> print (t)
[‘a’, ‘b’, ‘c’, ‘d’, ‘e’]

>>> t = [‘a’, ‘b’, ‘c’]
>>> del t[1]
>>> print (t)
[‘a’, ‘c’]

>>> t = [‘a’, ‘b’, ‘c’]
>>> t.remove(‘b’)
>>> print (t)
[‘a’, ‘c’]

Lists and string
>>> s = ‘string’
>>> t = list(s)
>>> print (t)
[‘s’, ‘t’, ‘r’, ‘i’, ‘n’, ‘g’]

>>> s = ‘string-string-string’
>>> delimiter = ‘-‘
>>> s.split(delimiter)
[‘string’, ‘string’, ‘string’]

>>> t = [‘string1’, ‘string2’, ‘string3’]
>>> delimiter = ‘  ‘
>>> delimiter.join(t)
‘string1 string2 string3’


A dictionary is a mapping between a set of indices (which are called keys) and a set of values.

>>> ita2eng = dict()
>>> ita2eng = {‘uno’: ‘one’, ‘due’: ‘two’, ‘tre’: ‘three’}
>>> print (ita2eng[‘due’])

Example of a function to count the numerosity of a letters in a string
def histogram(s):
d = dict()
for c in s:
if c not in d:
d[c] = 1
d[c] += 1
return d

Example of a function to obtain a key from a value
def reverse_lookup(d, v):
for k in d:
if d[k] == v:
return k
raise ValueError

A dictionary is implemented using a hashtable.

A hash is a function that takes a value (of any kind) and returns an integer. Dictionaries use these integers, called hash values, to store and look up key-value pairs.

This system works fine if the keys are immutable, so lists and dictionaries cannot be used as a key (but can be used as values).


Syntactically, a tuple is a comma-separated list of values:

>>> t = ‘a’, ‘b’, ‘c’, ‘d’, ‘e’

A tuple is a sequence of values. The values can be any type, and they are indexed by integers, so in that respect tuples are a lot like lists. The important difference is that tuples are immutable.

>>> t = tuple(‘string’)
>>> print (t)
(‘s’, ‘t’, ‘r’, ‘i’, ‘n’, ‘g’)

>>> print (t[0])
>>> print (t[1:3])
(‘t’, ‘r’)

>>> t[0] = ‘S’
TypeError: ‘tuple’ object does not support item assignment

Tuple assignment
>>> a, b = b, a

Functions accepting and returning multiple values
A function can only return one value, but if the value is a tuple, the effect is the same as returning multiple values.

Functions can take a variable number of arguments. A parameter name that begins with * gathers arguments into a tuple:

def printall(*args):
print args

The complement of gather is scatter. If you have a sequence of values and you want to pass it to a function as multiple arguments, you can use the * operator

>>> t = (7, 3)
>>> divmod(*t)
(2, 1)

Lists and tuples
>>> s = ‘abc’
>>> t = [0, 1, 2]
>>> zip(s, t)
[(‘a’, 0), (‘b’, 1), (‘c’, 2)]

Dictionaries and tuples
Dictionaries have a method called items that returns a list of tuples, where each tuple is a key-value pair.

>>> d = {‘a’:0, ‘b’:1, ‘c’:2}
>>> t = d.items()
>>> print (t)
[(‘a’, 0), (‘c’, 2), (‘b’, 1)]

Tuples can be used to initialize a new dictionary:

>>> t = [(‘a’, 0), (‘c’, 2), (‘b’, 1)]
>>> d = dict(t)
>>> print (d)
{‘a’: 0, ‘c’: 2, ‘b’: 1}

It is common to use tuples as keys in dictionaries (primarily because you can’t use lists).

directory[name,surname] = number
for name, surname in directory:
print name, surname, directory[name,surname]

Comparing tuples
The relational operators work with tuples and other sequences; Python starts by comparing the first element from each sequence. If they are equal, it goes on to the next elements, and so on, until it finds elements that differ.


Read from file
>>>fp = open(‘C:/file.txt’)
>>>for line in fp:
>>>    print(line)

Write to file
>>>fp = open(‘C:/file.txt’,’w’)

Catching exceptions
A lot of things can go wrong when you try to read and write files. It is better to go ahead and try—and deal with problems if they happen—which is exactly what the try statement does.

fin = open(‘bad_file’)
for line in fin:
print line
print ‘Something went wrong.’

Class and Objects

A class is a user-defined type. A class definition creates a new class object.

>>>class Point(object):
>>>    “””Represents a point in 2-D space.”””


>>>print (p1.y)

Copy objects
import copy
p2 = copy.deepcopy(p1)

Class Methods
class Time(object):
def print_time(time):
print ‘%.2d:%.2d:%.2d’ % (time.hour, time.minute, time.second)
def increment(self, seconds):
seconds += self.time_to_int()return int_to_time(seconds)
def is_after(self, other):
return self.time_to_int() > other.time_to_int()

>>> start = Time()
>>> start.hour = 9
>>> start.minute = 45
>>> start.second = 00
>>> print_time(start)
>>> end = start.increment(1337)
>>> end.print_time()

Note that the subject, start, gets assigned to the first parameter of increment, self. The argument, 1337, gets assigned to the second parameter, seconds.

>>> end.is_after(start)

The init method (short for “initialization”) is a special method that gets invoked when an object is instantiated

# inside class Time:
def __init__(self, hour=0, minute=0, second=0):
self.hour = hour
self.minute = minute
self.second = second

__str__ is a special method, like __init__, that is supposed to return a string representation of an object.

# inside class Time:
def __str__(self):
return ‘%.2d:%.2d:%.2d’ % (self.hour, self.minute, self.second)

By defining other special methods, you can specify the behavior of operators on user defined types

Functions that can work with several types are called polymorphic. Polymorphism can facilitate code reuse. For example, the built-in function sum, which adds the elements of a sequence, works as long as the elements of the sequence support addition.


Python keywords are:

and del from not while as elif global or with assert else if pass yield break except import print class exec in raise continue finally is return def for lambda try

Leave a Reply

Notify of