0% found this document useful (0 votes)
17 views30 pages

Python3 Handout

This document provides an introduction and outline for a course on Python programming. It will cover Python basics like data types, functions, object-oriented programming, and modules. The objective is to explain how Python can be used for network-related applications and tools. It will introduce students to the Python environment and best practices for code editing and style. Key topics will include Python types like strings, lists, tuples; basic operations; formatted output; and PEP 8 coding guidelines. Students will get hands-on practice using the Jupyter Notebook environment.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
17 views30 pages

Python3 Handout

This document provides an introduction and outline for a course on Python programming. It will cover Python basics like data types, functions, object-oriented programming, and modules. The objective is to explain how Python can be used for network-related applications and tools. It will introduce students to the Python environment and best practices for code editing and style. Key topics will include Python types like strings, lists, tuples; basic operations; formatted output; and PEP 8 coding guidelines. Students will get hands-on practice using the Jupyter Notebook environment.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 30

Introduction to Python3

Redes Software
Grados familia Ing. Telecomunicación

Curso 2022-23

Departamento de Ingeniería Telemática

Pedro A. Aranda Gutiérrez


Universidad Carlos III de Madrid
[email protected]

Materials taken from the SDN/NFV Master @ UC3M

1 / 60

Outline

1 Introduction

2 First steps in Python world: basic types

3 Functions and flow control

4 Object-oriented Programming

5 Modules, libraries, etc.

6 Practising with the Jupyter Notebook

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

So. . . how are we going to do this?


• We have three main blocks
1. Language basics
2. Object orientation
Classes
3. Libraries
Both internal and external
• Everything you see can be checked live

4 / 60
Before we start

• The editor question


▶ The right configuration is critical
▶ Avoid problems, stick to these basis rules:
1. Never use tabs, always use spaces
2. An indentation level is equivalent to four (4) spaces
3. Line termination is ’line feed’ only (No CR added)
• Quick tests can be done from the Command Line Interface (CLI)
▶ Nicest feature in Python is that we don’t have a compile step in the development cycle
▶ But his is also the nastiest feature: you don’t see errors until you execute the code
Errors may sit there latent for quite some time (!)

• To IDLE or nor to IDLE . . .


▶ IDLE can be a nice way for not-so-quick tests
▶ However, get used to the edit-execute cycle directly

5 / 60

More things about the editor


Nice things to make your life easy

• 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?

• PEP-8 is a set of guide-lines to help you write code


• Why?
▶ “Readability counts”. [3]
• There are established conventions in the Python community
▶ Write well from the beginning and avoid grief further on
• It also explains why certain things need to be done the way you are told to do them.
• What are Python Enhancement Proposals (PEPs)?
▶ As Python evolves, new features are discussed and eventually introduced
▶ The process is documented in Python Enhancement Proposals
• Other interesting PEPs:
▶ A PEP is a PEP is a PEP: PEP-0 or the PEP index [5]
▶ PEP-484: Type Hints [2] as a way of ’typifying’ Python

7 / 60

Outline

1 Introduction

2 First steps in Python world: basic types

3 Functions and flow control

4 Object-oriented Programming

5 Modules, libraries, etc.

6 Practising with the Jupyter Notebook

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

My first Python program


How to prepare your file - II
• Once you have created the header, leave an empty line and start editing your code
#!/usr/bin/env python3
# -*- coding: utf-8 -*-

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

• modulo operation to get the rest of an integer division


print(6 % 4)
2
• Power
x=3
print(x**2)
9

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

• It is strongly recommended to use single quote (’)


mensaje = 'Hello world'
▶ Although you may use double quotes (") like in C, Emacs Lisp et.al.
• Prefixes used to mark special kinds of strings
▶ Regular expressions (with the re module) use the r (raw) prefix:
busca_numero = r'[0-9]+'
▶ Formatting: use the f prefix to generate formatted strings
value = 5
print(f'value is {value}')
print(f'value is {value:02d}')
value is 5
value is 05

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 = ()

• Lists are equivalent to arrays in other languages


▶ Lists can be multi-dimensional
• Tuples share some common features:
▶ To access single elements, the indices are integers and start by 0
mydemo = ( 3, 4, 5 , 7 )
# mydemo = [ 3, 4, 5 , 7 ]
print(mydemo[0])
3

17 / 60

Python3 types
Strings are lists

• Strings are lists and substrings are extracted as index ranges


message = 'The value is 3'
print(f'message="{message}"')
print(f'The first character is message[0]={message[0]}')
print(f'A word: message[4:9]="{message[4:9]}"')
print(f'The first 5 characters: message[:5]="{message[:5]}"')
print(f'Starting from the 8th character: message[9:]="{message[9:]}"')
message="The value is 3"
The first character is message[0]=T
A word: message[4:9]="value"
The first 5 characters: message[:5]="The v"
Starting from the 8th character: message[9:]=" is 3"

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

2 First steps in Python world: basic types

3 Functions and flow control

4 Object-oriented Programming

5 Modules, libraries, etc.

6 Practising with the Jupyter Notebook

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

Flow control: loops


for and while
• Python has two loop forms
for var in list_of_values:
body

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

Flow control: loops - III


Taking control of a loop exit: else

• 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

print('my_fun returns ',my_fun(3,4))


print('my_fun returns ',my_fun(1,2,nvar="car"))
In my_fun(): 3 4 None
my_fun returns None
In my_fun(): 1 2 car
my_fun returns car

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

• finally is optional and will always be executed if present

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

2 First steps in Python world: basic types

3 Functions and flow control

4 Object-oriented Programming

5 Modules, libraries, etc.

6 Practising with the Jupyter Notebook

33 / 60

Introduction

• In Python3 almost everything is an object


• You work with instances of a class
• Classes have methods and attributes:
▶ methods are functions
▶ attributes are variables exposed to other parts of the program

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 __init__(self, x=0, y=0):


self.x = x
self.y = y

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 __init__(self, x=0, y=0):


self.x = x
self.y = y

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

Inheritance, extending classes - Ia


Let’s go 3-D

• Now let’s extend the Point class from 2D to 3D:


class Point3D(Point):
z = 0
def __init__(self, x=0, y=0, z=0):
super().__init__(x=x, y=y)
self.z = z

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()

• super from Latin: above

class Point:

class Point3D(Point):

39 / 60

Inheritance, extending classes - II


Looking inside the class
• We have introduced (implicit) methods that are present in classes:
▶ __init__(), __repr__()
▶ and seen that we can override them to adjust them to our needs
▶ These are the implicit methods of any class derived from object
class P:
pass
__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__,

• 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

• A decorator is a Python construct to enrich the language syntax


• Python3 has some default decorators
▶ including @property
• But they can also be user-defined
▶ Mininet has some, so remember during the labs

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

Other decorators you will meet in the labs - I


@property and @setter together

• @<>.setter is the complementary decorator to @property:


import math
class Point():
def __init__(self, x=0, y=0):
self.x,self.y = x,y
def __repr__(self):
return f'({self.x},{self.y})'
@property
def x(self):
return self._x
@x.setter
def x(self,x):
self._x = x
@property
def y(self):
return self._y
@y.setter
def y(self,y):
self._y = y
p = Point(3,4)
print(f'p = {p}', end = ' ... ')
p.x = 10
print(f'p = {p}')
p = (3,4) ... p = (10,4)

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

Lists and dictionaries the OO-way


Methods to manipulate lists
• Lists and their append() method
▶ A way to add an object (and just 1) at the end of a list
lista = [ 0, 1, 2 ]
print (lista)
lista.append(3)
print (lista)
lista.append('What the ... ???')
print (lista)
lista.append([4,5,6])
print (lista)
[0, 1, 2]
[0, 1, 2, 3]
[0, 1, 2, 3, 'What the ... ???']
[0, 1, 2, 3, 'What the ... ???', [4, 5, 6]]

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

Lists and dictionaries the OO-way - III


Putting objects in a list and removing them

• You can put an object in a specific point in a list


lista.insert(index, value)
• You can remove an object from a list
lista.remove(value) # remove first object with value <value>
lista.pop() # remove last object of the list
lista.pop(index) # remove object at position <index>
• Example
lista = [ 1, 2, 3 , 2 ]
lista.remove(2)
print (lista)
print (lista.pop(),lista)
lista.insert(1,2)
print (lista)
print (lista.pop(2),lista)
print (lista)
[1, 3, 2]
2 [1, 3]
[1, 2, 3]
3 [1, 2]
[1, 2]

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

• Dictionaries are managed in a similar way


• Method .get() allows you to avoid ’Key error’ exceptions for non-existent keys
▶ It will result None for non-existent keys
fruit = {
'yellow': 'banana',
'green': 'kiwi',
'red': 'cherry',
}
try:
colour = 'blue'
cake = fruit.get(colour,'??')
if cake == '??':
print (f'{cake} No {colour} fruit to make a cake, sorry')
else:
print (f'Do you want {cake} cake?')
cake = fruit[colour]
except Exception as e:
print(f'Exception : {str(e)}')
?? No blue fruit to make a cake, sorry
Exception : 'blue'

50 / 60
Outline

1 Introduction

2 First steps in Python world: basic types

3 Functions and flow control

4 Object-oriented Programming

5 Modules, libraries, etc.

6 Practising with the Jupyter Notebook

51 / 60

Stock modules included in Python3

• We have already seen an example of a module included in the Python distribution


import math
...
def distance(self):
return math.sqrt(self.x**2 + self.y**2)
• You can import the whole module or specific objects or methods
from math import sqrt as root

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

with ZipFile('../python3.zip', mode='r') as fzip:


for elem in fzip.namelist():
print(elem)
python3/Makefile
python3/packages.tex
python3/acronyms.tex
python3/python3.pdf
python3/python3.org
python3/logos/uc3m-2021.jpg
python3/logos/uc3m-2021.png
python3/logos/fondo-2021.png
python3/logos/fondo-2021.jpg
python3/python3-handout.pdf
python3/python3.bib
python3/beamerthemeUC3M2022.sty
python3/figures/nglinks.png
python3/figures/ag-notebook.png

53 / 60

Other examples of external libraries


To infinity and . . .
• Networking:
▶ scapy
Network traffic analysis and generation
▶ Mininet and Ryu
This is your lab
• Maths
▶ Pandas https://pandas.pydata.org
Numerical and statistical processing
▶ SciKIT: https://scikit-image.org
Image analysis and processing
• Other things:
▶ OpenPXYL: https://openpyxl.readthedocs.io/en/stable/
Read and generate Excel files with Python
▶ BLEAK https://github.com/hbldh/bleak
Bluetooth stack to communicate with bluetooth devices
• etc.

54 / 60
Installing libraries
using pip3 to enrich our Python environment

• The recommended way to install external Python libraries is using pip3


• Should be installed in your system with your Python3 distribution
▶ Notable exception is Linux (Debian derivatives like Ubuntu)
sudo apt install python3-pip
• There is a directory Web page with modules that you can use
▶ https://pypi.org
• Check your OS to see whether it distinguishes user and system-wide installation
• How to use pip3
pip3 install lxml
# or
python3 -m pip install lxml
• CAVEAT: It is not recommended that you install pip modules with administrator privileges!

55 / 60

Outline

1 Introduction

2 First steps in Python world: basic types

3 Functions and flow control

4 Object-oriented Programming

5 Modules, libraries, etc.

6 Practising with the Jupyter Notebook

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

Using Jupyter notebooks inside the Virtual Machine

• Get the URL of the Jupyter server:


docker logs --tail 3 notebook
▶ Right-click on it to open the Jupyter UI in the Virtual Machine (VM)

• 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

[1] "eriky", ed. Python for Programmers. Nov. 2022. URL:


https://wiki.python.org/moin/BeginnersGuide/Programmers.
[2] Łukasz Langa Guido van Rossum Jukka Leftosalo. PEP 484 - Type hints. Sept. 2014. URL:
https://peps.python.org/pep-0484/.
[3] Tim Peter. The Zen of Python. 2004. URL: https://peps.python.org/pep-0020/.
[4] Python reference guide. 2023. URL: https://docs.python.org/3/library/index.html.
[5] python-dev. PEP 0 - Index of Python Enhancement Proposals. July 2000. URL: https://peps.python.org/.
[6] Kenneth Reitz. PEP 8 — the Style Guide for Python Code. Aug. 2019. URL: https://pep8.org/.

60 / 60

You might also like