Python3 Handout
Python3 Handout
Redes Software
Grados familia Ing. Telecomunicación
Curso 2022-23
1 / 60
Outline
1 Introduction
4 Object-oriented Programming
2 / 60
Objective
• Python is well established in almost any field you may dare to think of
▶ Network-related application field
Mininet network emulation scenarios
control programs for the Ryu SDN controller
scapy: an environment to generate, manipulate and dissect IP packets
...
▶ Applications outside the network world
Python is well-established in most fields you can think of
Use Python to program statistics or numerical analysis
Interact with general purpose tools like Excel, Word, Powerpoint, etc.
...
• Resources to start with Python:
▶ There are plenty
▶ You can find a long list in the Python Beginner’s Wiki page [1]
3 / 60
4 / 60
Before we start
5 / 60
• The editor should recognize Python files and configure itself automatically
• The editor should be able to check the things we write
▶ Alert when things are not right
▶ Fix indentation
• The next step: Language Server Protocol (LSP)
▶ LSP is a server-client model
▶ The server analyses the Python code
Flags when code doesn’t comply with PEP-8 [6]
Provides code Autocompletion hints
Provides information about variables, functions, etc.
▶ The client is part of your editor
Interacts with the server
Shows hints, marks errors
Uses the server to reformat code, rename variables, etc.
6 / 60
PEP-8?
7 / 60
Outline
1 Introduction
4 Object-oriented Programming
8 / 60
My first Python program
Or how to prepare your file
• Open the text editor
▶ Most allow you to open an empty file without name
Activate the Python editing mode
▶ or open a new file with a file with ’.py’ as extension to automatically activate the Python editing mode
• Start by adding the Python header, which will always be:
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
• If your editor supports code snippets, this should be your first Python snippet
• Some Operating Systems will load the Python interpreter to execute the program
▶ Linux, macOS
▶ You need to set the executable mode bit on the created file
chmod a+x <file.py>
9 / 60
print('Hello world!')
Hello world!
• Linux or macOS: (Optionally) make it executable and execute it directly:
$ chmod +x hola.py
$ ./hola.py
Hello world
10 / 60
Python3 types
Basic types
• Numbers
▶ There is no difference between integers and floating point numbers
• Objects
▶ Strings
▶ Lists
▶ Dictionaries
▶ Tuples
▶ etc.
▶ None: the empty object
Normally flags errors
May raise exceptions and terminate the program
11 / 60
Python3 types
Numbers: basics operations
• Addition, subtraction, multiplication and division
▶ CAVEAT: use int() to get an integer division result
n=3
print(n/3)
print(int(n/3))
1.0
1
12 / 60
Python3 types
Numbers - II
• Bit-wise logic operations:
flag = 7
print ('AND: {:4b} & {:4b} = {:4b}'.format(flag, 14, flag & 14))
print ('OR: {:4b} | {:4b} = {:4b}'.format(flag, 8, flag | 8))
print ('XOR: {:4b} ^ {:4b} = {:4b}'.format(flag, 4, flag ^ 4))
AND: 111 & 1110 = 110
OR: 111 | 1000 = 1111
XOR: 111 ^ 100 = 11
• Mathematical functions are in the math module
import math
print(math.sqrt(2))
print(math.pi)
1.4142135623730951
3.141592653589793
13 / 60
Python3 types
Numbers - III
• Uniform auto-increment and auto-decrement
▶ No short form like ++ or -- in C(++)
▶ You don’t have to worry about pre/post auto-in/de-crement
n = 3
print(n)
n += 4
print(n)
n -= 1
print(n)
3
7
6
14 / 60
Python3 types
Strings
15 / 60
Python3 types
Strings: formatted strings
• The generalised way to include a variable is {<index>:<format specifier>}
▶ For the .format() method:
Omitting <index> consumes variables to .format() sequentially
Flags errors (for example: format string expects 2 variables and you only pass 1)
from math import sqrt, pi
print(f'{" ".join(["-----"]*4)}')
print('{0:<5s} {0:5s} {0:^5s}'.format('asi'))
print(f'{1:<5d} {2:5d} {3:^5d} {4:05d}')
print('{:5.1f} {:.2f} {:f}'.format(sqrt(2), sqrt(30), pi))
----- ----- ----- -----
asi asi asi
1 2 3 00004
1.4 5.48 3.141593
16 / 60
Python3 types
Lists and tuples
• To create an empty list or an empty tuple
empty_list = []
empty_tuple = ()
17 / 60
Python3 types
Strings are lists
18 / 60
Python3 types
Dictionaries
• Can be understood as lists, but indices can have any type
• The index is a key to access a value
• To create an empty dictionary:
newdict = dict()
• A dictionary with keys and values:
healthy = {
'green' : 'apple',
'yellow': 'banana',
'red' : 'strawberry'
}
colour = 'red'
fruit = healthy[colour]
print(f'A {colour} fruit: {fruit}')
A red fruit: strawberry
• We will see more. . .
19 / 60
Python3 types
Tuples
• Functions can return any number of values
• When two or more values are returned, the function returns a tuple
▶ Which basically works as a list
def check():
return 1, 2, 3
tuple = check()
print(tuple, ' ', tuple[0], tuple[1], tuple[2])
(1, 2, 3) 1 2 3
20 / 60
Python3 types
Tuples - II
• With the extra convenience that you may ignore some of the values returned
import os
fname = 'test.py'
print(os.path.splitext(fname))
_,ext = os.path.splitext(fname)
print (f'The file extension is {{{ext}}}')
('test', '.py')
The file extension is {.py}
21 / 60
Outline
1 Introduction
4 Object-oriented Programming
22 / 60
Logical expressions
Taking decisions: if elif else
• Flow control allows to execute parts of the code depending on specific conditions
value = 1
if value ==1 :
print ('Number 1')
else:
print ('This was NOT number 1')
Number 1
• We can check more than one condition
▶ But making sure they are mutually exclusive
▶ There is no case construct as such
value = 1
if value == 1:
print ('Number 1')
elif value is None:
print ('Why is value None?')
else:
print ('Neither None nor 1')
Number 1
23 / 60
while condition:
body
• A for loop:
for i in [2,3,4]: #list(range(2,5)):
print(i, end=' ')
2 3 4
• while loops are similar
i=0
while i < 2:
print(i,end=' ')
i += 1
0 1
• To avoid infinite loops, make sure the condition is met
▶ i.e. with an autoincrement
24 / 60
Flow control: loops - II
continue and break
• You can finish the execution of a loop prematurely with break:
for i in list(range(10)):
print(i,end=' ')
if i == 5:
break
0 1 2 3 4 5
• You can finish the execution of an iteration prematurely with continue:
for i in list(range(10)):
if i < 5:
continue
print(i,end=' ')
5 6 7 8 9
25 / 60
• Use else to check that the loop did not exit prematurely
for i in list(range(5)):
if i < 3:
continue
print (i, end=' ')
else:
print('\nWonderful, you reached the end of the loop!')
3 4
Wonderful, you reached the end of the loop!
• And now for a while:
i=0
while i < 10:
print (i,end=' ')
i += 1
if i == 3:
break
else:
print('\nCool, we have finished!')
0 1 2
26 / 60
Flow control: loops - IV
The range
• range() is a collection you need to transform into a list with list()
• range(n) is the collection of integers between 0 and n-1
• range(m,n) is the collection of integers between m and n-1
• range(m,n,k) is the collections of integers m, m+k, m+2k,. . . which are less than n
print(range(8))
print(list(range(8)))
print(list(range(3,8)))
print(list(range(3,8,2)))
range(0, 8)
[0, 1, 2, 3, 4, 5, 6, 7]
[3, 4, 5, 6, 7]
[3, 5, 7]
27 / 60
More on lists
Questions from the audience
• Loop counters
▶ You can use elements from any list, as long as you know what to do with them
for msg in ['hello','world']:
print(msg)
healthy = {
'green' : 'apple',
'yellow': 'banana',
'red' : 'strawberry'
}
for colour in healthy.keys():
print (f'A healthy {colour} fruit: {healthy[colour]}')
hello
world
A healthy green fruit: apple
A healthy yellow fruit: banana
A healthy red fruit: strawberry
28 / 60
Functions (methods)
• Python doesn’t distinguish between function and procedure. Everything is a function.
▶ A function exported by an object is a method
• If you don’t return anything explicitly, it is assumed that None is returned
• Additionally, you can have unnamed and named parameters
▶ You always start with the unnamed parameters
▶ named parameters are assigned a default value in the function declaration
▶ You must include all unnamed parameters in your call
• Example:
def my_fun(var1, var2, nvar=None):
print ('In my_fun():',var1, var2, nvar)
return nvar
29 / 60
Exceptions
Error treatment in your program
• Python3 will stop the execution and exit the program on errors
▶ However, you can capture and treat the errors internally
try:
myval = 0
result = 1/myval
print (f'Result: {result}')
except Exception as e:
print(f'Caught exception `{str(e)}`')
finally:
print('And we continue')
Caught exception `division by zero`
And we continue
• Code between try and except is executed
▶ If an Exception is raised
the code in the try block is exited and
the except code block is executed
▶ Exception is them most general exception type
You may include different except code blocks for different exception types
Then you may have an except Exception: at the end to handle all Exceptions you didn’t specify explicitly before
30 / 60
Useful constructs
File handling: with
• Files have a specific handling procedure:
▶ Open (or create), read (or write) and close
▶ If you forget to close a file, it may have nasty consequences
▶ If you open too many files, the OS may not like it
• with
1. Allows you to concentrate all file operations in a code block
2. And close the file automatically when the code block is exited
• For example:
with open('fichero','r') as fichero:
for line in fichero:
for palabra in linea.split(' '):
print(palabra)
print (f'Last line {line}')
31 / 60
Useful constructs
with and try:
• And putting try and with together, we can have highly expressive code:
try:
with open('fichero','r') as fichero:
for line in fichero:
print(line)
except FileNotFoundError as fnfe:
print(f'Error: {str(fnfe)}')
except:
print('Other error')
Error: [Errno 2] No such file or directory: 'fichero'
32 / 60
Outline
1 Introduction
4 Object-oriented Programming
33 / 60
Introduction
34 / 60
Classes
Introduction - An example: points in a 2-D space
import math
y
class Point:
x = 0
y = 0
def distance(self): ()
nce
return math.sqrt(self.x**2 + self.y**2)
dista
p1 = Point()
p1.x = 4
p1.y = 3
print(f'Distance from p1 to the origin: {p1.distance()}') x
Distance from p1 to the origin: 5.0
35 / 60
Classes - II
The __init__() method
• We can initialise the instance when we instantiate the class
▶ Using the __init__() method
import math
class Point:
x = 0
y = 0
def distance(self):
return math.sqrt(self.x**2 + self.y**2)
p1 = Point(x=3, y=4)
print(f'Distance from (0,0) to ({p1.x},{p1.y}) is {p1.distance()}')
Distance from (0,0) to (3,4) is 5.0
36 / 60
Classes - III
The __repr__() method
• You can define the way you represent (i.e. print) the instance
▶ Overriding the __repr__() method
import math
class Point(object):
x = 0
y = 0
def __repr__(self):
return f'({self.x},{self.y})'
def distance(self):
return math.sqrt(self.x**2 + self.y**2)
p1 = Point(x=3, y=4)
origin = Point()
print(f'The distance from {origin} to {p1} is {p1.distance()}')
The distance from (0,0) to (3,4) is 5.0
37 / 60
def __repr__(self):
return f'({self.x},{self.y},{self.z})'
def distance(self):
return math.sqrt(super().distance()**2 + self.z**2)
p2 = Point3D(x=3,y=4,z=9)
origin=Point3D()
print(f'Point {p2} is {p2.distance():.3f} away from {origin}')
Point (3,4,9) is 10.296 away from (0,0,0)
38 / 60
Inheritance, extending classes - Ib
Explanation
• We defined the base object (i.e. the 2D point)
Class Point:
...
• We extended it to a 3D point
class Point3D(Point):
...
• And every time we needed or wanted to reuse things we had already defined in Point, we used
super()
class Point:
class Point3D(Point):
39 / 60
• And this is what happens when you create an object with attributes or methods
class P2:
p = None
def distance(self):
return 1
__class__, __delattr__, __dict__, __dir__, __doc__, __eq__, __format__,
__ge__, __getattribute__, __gt__, __hash__, __init__, __init_subclass__, __le__,
__lt__, __module__, __ne__, __new__, __reduce__, __reduce_ex__, __repr__,
__setattr__, __sizeof__, __str__, __subclasshook__, __weakref__, distance, p,
40 / 60
Decorators
Decorators: making code more readable
41 / 60
Decorators
An example. . .
• Let’s revisit the 2D Point class and define the distance to the origin as a property:
class Point:
_x = 0
_y = 0
def __init__(self, x=0, y=0):
self._x = x
self._y = y
def __repr__(self):
return f'({self._x},{self._y})'
def distance(self):
from math import sqrt
return sqrt(self._x**2 + self._y**2)
@property
def r(self):
return self.distance()
p = Point(x=3,y=4)
print(f'{p} distance from origin is {p.distance()}')
print(f'{p} distance from origin is {p.r}')
(3,4) distance from origin is 5.0
(3,4) distance from origin is 5.0
42 / 60
Decorators
Or shorter. . .
class Point:
_x = 0
_y = 0
def __init__(self, x=0, y=0):
self._x = x
self._y = y
def __repr__(self):
return f'({self._x},{self._y})'
@property
def r(self):
from math import sqrt
return sqrt(self._x**2 + self._y**2)
p = Point(x=3,y=4)
print(f'{p} r={p.r}')
(3,4) r=5.0
• In this case we are referring to a class method as if it were an attribute
43 / 60
44 / 60
Other decorators you will meet in the labs - II
@staticmethod
• Some classes add static methods, i.e. invariant methods that do not depend on the instance
• You can signal them with the @staticmethod decorator
• And omit self in the method declaration
class Point():
def __init__(self, x=0, y=0):
self._x = x
self._y = y
def __repr__(self):
return f'({self._x},{self._y})'
@property
def r(self):
return Point.distance(self._x, self._y, 0.0)
@staticmethod
def distance(x, y, z):
import math
return math.sqrt(x**2 + y**2 + z**2)
p = Point(10,15)
print(f'{p} --> {p.r:.4f}')
(10,15) --> 18.0278
45 / 60
46 / 60
Lists and dictionaries the OO-way - II
• How can we join two lists?
▶ i.e. put one list at the end of another
▶ with the .extend() method
▶ Caveat: you may see examples with the + operator
lista = [ 0, 1, 2 ]
lista.extend([ 3, 4, 5 ])
print (lista)
[0, 1, 2, 3, 4, 5]
• And what about strings?
lista.extend('Hello')
print (lista)
[0, 1, 2, 3, 4, 5, 'H', 'e', 'l', 'l', 'o']
• So better use .append() if you need to append a string to a list
47 / 60
48 / 60
Lists and dictionaries the OO-way - IV
Otra forma de borrar elementos de una lista
• You can pop() elements from a list or use the Python keyword
▶ del
▶ With lists, use it like this
del lista[index] # to delete an element
del lista[range] # to delete a range of elements
• An example
lista = list(range(10))
del lista[3]
print (lista)
lista = list(range(10))
del lista[3:5]
print (lista)
print (list(range[3:5]))
[0, 1, 2, 4, 5, 6, 7, 8, 9]
[0, 1, 2, 5, 6, 7, 8, 9]
▶ CAVEAT del lista kills the whole list
49 / 60
Dictionaries
Avoiding exceptions
50 / 60
Outline
1 Introduction
4 Object-oriented Programming
51 / 60
print('{:6.4f}'.format(root(3.0)))
1.7321
▶ In the example, we have created an alias (root) for sqrt
• The Python reference guide [4] includes all available modules
52 / 60
Stock modules included in Python3
A (hopefully) useful example
• You have a ZIP file and want to list all files included in it
from zipfile import ZipFile
53 / 60
54 / 60
Installing libraries
using pip3 to enrich our Python environment
55 / 60
Outline
1 Introduction
4 Object-oriented Programming
56 / 60
Installing the Jupyter Notebook in the VM
• Make sure that the docker group exists and the user is in it
sudo addgroup --system docker
sudo usermod -aG docker $(whoami)
newgrp docker
▶ You only need to do this if the docker group does not exist
• Install Docker
▶ You can use the Docker snap, because you are not using system resources like files in the /etc directory, etc.
sudo snap install docker
• Install Jupyter notebooks Docker
▶ Using --network=host is useful if you want to install this in a Virtual Machine and access the notebook from your
host.
mkdir workbook
docker run -d -P --network=host --name notebook \
-v "$(pwd)/workbook":/home/jovyan/work jupyter/base-notebook
57 / 60
• Inside the VM
▶ Download and decompress the workbook from Aula Global
▶ Upload it to Jupyter (using the Jupyter UI)
58 / 60
Uninstalling Jupyter and Docker
• In order to clean up the VM for the next laboratories, you should kill and remove the container
▶ You can use docker without sudo, because your user is in the sudo group
docker ps -aq | xargs docker kill
docker ps -aq | xargs docker rm
• You can then remove the image or completely uninstall Docker until you need it again:
sudo snap remove --purge docker
59 / 60
Bibliography
60 / 60