SlideShare a Scribd company logo
1 of 95
Download to read offline
Firma convenzione
Politecnico di Milano e Veneranda Fabbrica
del Duomo di Milano
Aula Magna – Rettorato
Mercoledì 27 maggio 2015
Lesson 1: Introduction to PYNQ Platform
and Python language
Luca Cerina – luca.cerina@polimi.it
Ver. Updated – 22/11/2017
Luca Cerina, R.A. @ NECSTLab – DEIB
PYNQ Board
• 650Mhz dual-core
Cortex-A9 processor
• 512MB DDR3
• FPGA: ZYNQ
XC7Z020-1CLG400C
Per maggiori informazioni: http://www.tpynq.io/home.html
Luca Cerina, R.A. @ NECSTLab – DEIB
PYNQ Board
3
Communicaton over
ethernet
Jutpyter serverJutpyter server
Pynq APIPynq API
FPGA: programmabile logic
ARM Processor
PMODHDMI (out, in)
Audio
connectors
GPIO: leds, butoos, switches
Ethernet
Overlay
(base.bit)
Overlay
(base.bit)
USB
Micro SD
(Linux OS +
Jutpyter
notebook)
Pyoq Board
Luca Cerina, R.A. @ NECSTLab – DEIB
FPGA: Field Programmable Gate Arrays
A fully retprogrammable chitp in which diferent basic blocks,
like Look-Utp-Tables, Memory, and Flitp-Flotps internally
connects together to recreate comtplex digital circuits.
Luca Cerina, R.A. @ NECSTLab – DEIB
THE COMMUNITY FUNNEL
Atptplicaton
develotpers
Driver develotpers
Overlay designers
● Python on jutpyter
● Everything else
● Vivado SDK
● C/C++
● Python wratptpers
● Vivado/SDSoC
suite
● C/C++, VHDL
Luca Cerina, R.A. @ NECSTLab – DEIB
Hardware ioterfaces
Pynq provides:
• 2 Fully programmable PMOD connectors
• 1 Arduino compatible interface
• 1 HDMI and audio I/O
Luca Cerina, R.A. @ NECSTLab – DEIB
Hardware ioterfaces
Luca Cerina, R.A. @ NECSTLab – DEIB
LED, Butoos aod switches
Pynq provides:
• 6 LED commanded from Python (2 RGB)
• 2 Switches and 4 Buttons with readable state
Luca Cerina, R.A. @ NECSTLab – DEIB
WHAT IS AN OVERLAY
Overlays are “hardware libraries” that extends the Processing
System with a Programmable Logic design
Luca Cerina, R.A. @ NECSTLab – DEIB
WHAT IS JUPYTER
Project Jupyter is an open
source project was born out of
the IPython Project in 2014 as it
evolved to support interactive
data science and scientific
computing across all
programming languages.
Jupyter will always be 100%
open source software, free for
all to use and released under
the liberal terms of the modified
BSD license
Luca Cerina, R.A. @ NECSTLab – DEIB
WHAT IS PYTHON
• Python is a tprogramming language
• High level
• Intertpreted
• (weak) Dynamic Tytping
• Object-oriented
We’ll get more on this later
• Useful for fast tprototytping of atptplicatons and with code
readability in mind.
• Documentaton: https://www.tpython.org/doc/
Luca Cerina, R.A. @ NECSTLab – DEIB
SUGGESTED DEVELOPMENT PLATFORM
Luca Cerina, R.A. @ NECSTLab – DEIB
C vs PYTHON
C
- Low level
- Comtpiled
- Strong tytping
- Non object-oriented
Pythoo
- High level
- Intertpreted
- Weak tytping
- Object-oriented
Luca Cerina, R.A. @ NECSTLab – DEIB
C vs PYTHON
C
- Low level
- Comtpiled
- Strong tytping
- Non object-oriented
Pythoo
- High level
- Intertpreted
- Weak tytping
- Object-oriented
Extplicit memory allocaton
(tpointers management)
Imtplicit memory allocaton
(hidden to the user)
Luca Cerina, R.A. @ NECSTLab – DEIB
C vs PYTHON
C
- Low level
- Comtpiled
- Strong tytping
- Non object-oriented
Pythoo
- High level
- Intertpreted
- Weak tytping
- Object-oriented
file.cfile.c
gccgcc
Machine codeMachine code
file.tpyfile.tpy
Python intertpreterPython intertpreter
Intertpreted codeIntertpreted code
Luca Cerina, R.A. @ NECSTLab – DEIB
C vs PYTHON
C
- Low level
- Comtpiled
- Strong tytping
- Non object-oriented
Pythoo
- High level
- Intertpreted
- Weak tytping
- Object-oriented
int a;
a = 5; //Correct
a = “string”; //Error!!
a = 5 #Correct
a = “stringa” #Correct
a = 1.3 #Correct
Type must be known by the
compiler
No explicit type declaration
Luca Cerina, R.A. @ NECSTLab – DEIB
C vs PYTHON
C
- Low level
- Comtpiled
- Strong tytping
- Non object-oriented
Pythoo
- High level
- Intertpreted
- Weak tytping
- Object-oriented
void sort(int * array){...}
...
int vet[] = {1, 6, 4, 8, 9};
sort(vet);
vet = [1, 6, 4, 8, 9]
vet.sort()
sort is a functon of the object vet
and act on it
Luca Cerina, R.A. @ NECSTLab – DEIB
Pythoo syotax
• Variables do not need declaraton before usage
• ‘;’ are not necessary to end an instructon line,
• INDENTATION IS FUNDAMENTAL
• Code constructs (if-else, for lootps, etc…)
use ‘:’ + indentaton instead of ‘{‘
Indentaton is done with Tabs or Whitestpaces
• Comments are # (single line) or “”” (multline/docstring)
• INDENTATION IS FUNDAMENTAL
Luca Cerina, R.A. @ NECSTLab – DEIB
Exercise 0: Hello world (agaio)
print(“Hello world!”)
No need for I/O library imtport
Luca Cerina, R.A. @ NECSTLab – DEIB
Exercise 1: I/O
●
Read a number from command line, and
print if it is odd or even
●
Read a number from command line, add 5 to
it, and then save it in another variable as a
string. Then print it (hints int() and str()
functions)
Luca Cerina, R.A. @ NECSTLab – DEIB
Pythoo libraries
• As in C, it is possible to load libraries (modules) to extend
python functionalities
• Modules can be imported in various ways:
imtport os
#imtport namestpace of module os
imtport os as O
#imtport namestpace of module os with an alias O
from os imtport *
#imtport the entre namestpace
from os imtport curdir as CC
from os imtport listdir as LS
#imtport a stpecific element of the module
os.curdir
os.listdir(“Desktotp”)
O.curdir
O.listdir(“Desktotp”)
curdir
listdir(“Desktotp”)
CC
LS(“Desktotp”)
Luca Cerina, R.A. @ NECSTLab – DEIB
Libraries examples
• OS → operative system calls (e.g. cd, ls, shell functions)
• Numpy → exhaustive numerical library
Luca Cerina, R.A. @ NECSTLab – DEIB
Utlites
• help(obj) shows the object documentaton (atributes,
functons, behaviour, …)
• len(obj) returns the length of the object Not all objects have a
length!
• dir(obj) list all atributes and functons of obj
• tytpe(obj) returns the tytpe of the object
Luca Cerina, R.A. @ NECSTLab – DEIB
Exercise 2: I/O “type” check
●
Read anything from command line, and
verify (print) if the object is numeric,
alphanumeric or alphabetic
●
Read anything from command line, and if it
is alphanumeric, print it in uppercase
Luca Cerina, R.A. @ NECSTLab – DEIB
Pythoo basic types
tpi esempio
int 1, 2, 3
float 1.5, 2.2, 4.3
bool True, False
str “abc”, “string”
list [1, 2, 3, 4], [”abc”, “def”, “ghi”]
dict {key1: value1, key2: value2}
tutple (1, 2, 3, 4), (“abc”, “def”, “ghi”)
set {1, 2, 3, 4}, {“abc”, “def”, “ghi”}
List, dict, tutple and sets will be extplained later
Luca Cerina, R.A. @ NECSTLab – DEIB
Logical operators
Operaziooi C Pythoo
And logico && and
Or logico || or
Not logico ! not
Uguaglianza ==, != ==, !=, is, is not
Confronto <, >, <=, >= <, >, <=, >=
==, != verify if two objects have
the same value
is, is not verify if two objects are the
same object
Luca Cerina, R.A. @ NECSTLab – DEIB
If-else coostruct
• If-else basic structure (REMEMBER INDENTATION):
• Nested if-else constructs can be grouped using elif:
elif
Luca Cerina, R.A. @ NECSTLab – DEIB
Exercise 3: Calculator
●
Read two numbers (let’s assume them to be
float)
●
Ask the user the type of calculation to be
done
●
Execute it and print the result
●
Bonus! Allow the user to insert complex
numbers (X+Yj, hint: numpy)
Luca Cerina, R.A. @ NECSTLab – DEIB
While loop
• While loop syntax is identical to the C equivalent:
• Con! Python do not provide a do..while loop
• But! It is possible to insert a else branch at the exit of the while
loop
• The else branch is executed when the while condition
becomes False
Luca Cerina, R.A. @ NECSTLab – DEIB
Exercise 4: Maximum value
●
Let the user insert a certain number of
positive integers (NB check the type!)
●
Ask the user to continue the insertion of to
stop the loop
●
At the end of the loop print the maximum
value inserted
Luca Cerina, R.A. @ NECSTLab – DEIB
For loop
• For loop is different from the C equivalent
• A variable iterates on the elements of a sequence
• A sequence can be a lot of things:
• A list, dictionary or set
• A string
• An iterator
• Also the for loop supports else branch on exit
Luca Cerina, R.A. @ NECSTLab – DEIB
Iterators
• Iterators are objects that return a sequence of other objects one element at a
time using the method next()
• The classical iterator in the for loop is range()
• Fine parameter is mandatory, inizio and step are optional:
• Iteration goes from inizio to fine (excluded)
• Default ‘inizio’ is 0
• Default ‘step’ is 1
• ‘Step’ requires that ‘inizio’ is inserted
• If inizio > fine the loop is not executed, unless step is < 0
Luca Cerina, R.A. @ NECSTLab – DEIB
Exercise 5: Expooeotal
●
Read one base and one exponent (integer
and positive) and print the exponential.
●
Use both ‘**’ python operator and a for loop
Luca Cerina, R.A. @ NECSTLab – DEIB
Exercise 6: PI calculatoo
The PI value can be approximated as:
The integral value is calculated as sum of rectangles. The higher
the number of rectangles, the better the approximation.
Write a Python script that ask the number of intervals to the user,
calculate the PI value and calculate the error against the one
available in the numpy library (use the abs() function to obtain the
error)
Luca Cerina, R.A. @ NECSTLab – DEIB
Lists
• Lists are object, with variable dimension, that contains other objects in the
order they were inserted
• Lists can contain objects of diferent tytpe (bags of objects)
• Python-like lists do not exist in C, but C lists allow size extension
C
- Arrays cannot contain diferent
tytpes
- Arrays cannot change their size
Python
- Lists can contain diferent
objects
- A list can change its dimension
Luca Cerina, R.A. @ NECSTLab – DEIB
Lists creatoo
• A list can be created using:
• Otperator [ ]
• Functon list() … REMEMBER C reserved names
• Otperator [ ]
• [ ] create an emtpty list
• [val1, val2, val3] create a list
startng from inserted values
• Functon list()
• list() create an emtpty list
• list(iteratore) create a list
using the iterator elements
Luca Cerina, R.A. @ NECSTLab – DEIB
Read aod iosert elemeots
• Read
lista[index] like in C, index represents the position of the elements (0-
start counting)
• Insertion
• append(val) insert the element val at the end of the list
• insert(index, val) insert an element in the position index
Luca Cerina, R.A. @ NECSTLab – DEIB
Remove elemeots
• Removal
• Pop(index) remove the element index
• remove(val) remove the first occurrence of val
Luca Cerina, R.A. @ NECSTLab – DEIB
Traverse the elemeots
• To traverse a list we can use a for-loop like in C
• Or you can iterate directly on the list
• In this case i is the value of every element in the list
Luca Cerina, R.A. @ NECSTLab – DEIB
Exercise 7: list maoagemeot
●
Write a program that given a list of integer
numbers, print the list in reverse order
●
Modify the program to save the reversed list
into another list object, then print it
●
Bonus! Do it without using a loop (hint
lookup the list functions)
Luca Cerina, R.A. @ NECSTLab – DEIB
Exercise 7: possible solutoos
●
Lists allow negative indexing
●
The function reverse() on the list revert the object itself.
Attention! Reverse is an in-place function and directly
modify the object instead of returning another one
Luca Cerina, R.A. @ NECSTLab – DEIB
List coocateoatoo
• You can merge or concatenate two lists using
operator +
• It is possible to replicate a list N times using the
multiplication operator
Luca Cerina, R.A. @ NECSTLab – DEIB
Lists of Lists
• A list can be defined inside another list
• To access an element inside you have to access the first level list, and
then the element inside it
Luca Cerina, R.A. @ NECSTLab – DEIB
Lists of Lists
• Python matrices can be defined as a list of lists
• The outer list contains the rows of the matrix, the inner ones the
elements of the columns related to that row
• Examtples of matrix creatons
• It is tpossible to create “matrices” with rows of diferent lengths
Luca Cerina, R.A. @ NECSTLab – DEIB
List compreheosioo
• List comtprehension is a method that allows to build list in a fast and
comtpressed manner
• A list is created startng from the descritpton writen inside [ ]
• x indicate the value that we want to insert in the list
• The value inserted can be the result of an otperaton, or if conditons
Luca Cerina, R.A. @ NECSTLab – DEIB
Teroary operator
• This list comtprehension relies on a ternary otperator, i.e. an otperator
that returns a certain value based on a conditon being true or false
• If cooditoo is true, the outtput of this istructon is value cood_true,
otherwise it is value cood_false
Luca Cerina, R.A. @ NECSTLab – DEIB
Exercise 8: list compreheosioo
●
Write a program that given integer N, creates
a matrix with all odd numbers in a row, and
all even numbers in the second row
●
Given two dice, one with N faces, one with M
faces, generate all the possible combinations
(hint: it’s a list of tuples)
●
Given a list of integers, generate a new list
with only the elements > than the average
Luca Cerina, R.A. @ NECSTLab – DEIB
Exercise 8: solutoo
●
Combs = [(x,y) for x in range(1,N+1) for
y in range(1, M+1)]
●
Input = [1,2,3,4,5,6,7,8,9,10]
average = sum(Input)/len(Input)
Output = [x for x in Input if x>average]
Luca Cerina, R.A. @ NECSTLab – DEIB
Fuoctoos
• Functons are reusable tportons of tprogram, which can be called when
necessary
• A Pythoo functon can receive 0 or more parameters and generate 0 or
more outputs
• Diference between Python and C functons
• WITH GREAT POWER COMES GREAT RESPONSIBILITY!!!
C
- Functons can return at most one
result
- It is necessary to declare the tytpe
of both tparameters and result
- If necessary, it is tpossible to
define the functon tprototytpe
Python
- Functons can return more results
- It is not necessary to declare the tytpe
of either tparameters or result
- Functons are defined/redefined
dynamically: no tprototytpes
Luca Cerina, R.A. @ NECSTLab – DEIB
Defoitoo aod call
• To define a functon use the keyword def followed by the functon
name and its intput names (tpay atenton to the ending “:” and code
indentaton!):
• A functon call is executed stpecifying the functon name followed by
the tpossible intputs
• NOTE: at the moment of a functon call, the functon has to be
defined
Luca Cerina, R.A. @ NECSTLab – DEIB
Parameters
• Let us distnguish between tparameter tpassage with immutable and mutable types
• Immutable tytpes are tpassed by copy to the functons:
• The functon receives a cotpy of the tparameters
• Changes to the tparameters will not be seen outside the functon
• Mutable tytpes are tpassed by refereoce to the functons:
• The functon receives the reference to the tparameters (like for C arrays)
• Changes to the tparameters are seen outside the functon
Immutable types Mutable types
int list
float dict
bool set
str
tutple
Luca Cerina, R.A. @ NECSTLab – DEIB
Returo values
To return a result, it is necessary to use the keyword returo setparatng
the returned values with a comma
Luca Cerina, R.A. @ NECSTLab – DEIB
Exercise 9: fuoctoos
●
Write a function that sums all the elements in
a list
●
Write a function that calculates the factorial
of a number
●
Rewrite the integral program (lesson 1) into
a function, and return both integral value and
error to the user
Luca Cerina, R.A. @ NECSTLab – DEIB
Dictooaries
• Python dictonaries are a very tpowerful tool that allows to organize data as <key,
value> coutples
• Given a key, it is tpossible to ask the dictonary to tprovide the related value (if it exists)
• Key must be an immutable tytpe (int, float, str, …) while the value may assume any tytpe
• Dictonaries are commonly used to store data associatons:
• Given the first and last name of a tperson (key), retrieve his/her tphone number
(value of iot type)
• Given a class name (key), retrieve the list of teachers who have taught that class
(value of list type)
• Given a city name (key), retrieve the tphone book of that city inhabitants (value
of dictooary type)
Luca Cerina, R.A. @ NECSTLab – DEIB
Dictooary creatoo
• A dictonary may be created in two ways:
• {} otperator
• Functon dict()
• Examtples of creaton with {} otperator
• Examtples of creaton with functon dict()
Luca Cerina, R.A. @ NECSTLab – DEIB
Add, modify, remove
• To add an element to a dictonary or edit an already existng one, use
square brackets:
• To remove an element from a dictonary startng from its key, use
pop(key):
Luca Cerina, R.A. @ NECSTLab – DEIB
Access elemeots
• The number of elements in a dictonary can be obtained using
leo(dictooary)
• To read the value correstponding to a key use square brackets
• To verify whether a key exists or not, use the io otperator:
• Dictonary keys are iterable!
Luca Cerina, R.A. @ NECSTLab – DEIB
Classes
• Classes are data structures whose purpose is to contain
different types of variables and functions useful to provide
functionalities related to the kind of data to be represented
• Differently from C struct, classes may also contain functions
• An instance of a class is called object
C Python
Declaraton of
variables or functons
Luca Cerina, R.A. @ NECSTLab – DEIB
Namespace
• When a class (or a function) is created, the declared
variables/functions lay within the space of names (namespace)
generated for that class/function
• The namespace is a mapping from names to objects (like a
dictionary) that allows to invoke both the attributes and functions
defined within that namespace
• For instance, when the Python interpreter starts, some functions
are already available inside the initial namespace, like print()
• Is it possible to add functions/attributes and other namespaces
to a namespace through import command
Luca Cerina, R.A. @ NECSTLab – DEIB
Scopes
• The scope is a textual region of a Python program where it is
possible to directly invoke attributes/functions of a namespace
• Attributes/functions of a class can be directly called only within
the class itself, while, from the outside, it is necessary to use
an object of the class to call them (through “.” operator)
• Within a scope, it is also possible to redefine
attributes/functions defined in outer scopes
Luca Cerina, R.A. @ NECSTLab – DEIB
Scope example
global var var redefined by
test_scope
Through global,
test_scotpe edits var
Luca Cerina, R.A. @ NECSTLab – DEIB
Class defoitoo
• In order to define a class, the keyword class is required:
class className:
• Within the class definition, it is possible to declare attributes
and functions
self tparameter is a reference to the class
itself from within the class
Object creaton
self has not to be tpassed as argument when
invoking class functons
Luca Cerina, R.A. @ NECSTLab – DEIB
Class defoitoo with __ioit__
• It is possible to define within a class a special function called
__init__ whose purpose is to initialize class attributes during
its creation
• The attributes have not to be previously declared
i, a and b were not declared yet
The values of a and b have to be
tpassed during object creaton
Luca Cerina, R.A. @ NECSTLab – DEIB
Exercise 11: class creatoo
●
Write a class rectangle with two attributes
(one per side)
●
Define a function that returns the rectangle’s
area
●
Define a function that returns the rectangle’s
perimeter
Luca Cerina, R.A. @ NECSTLab – DEIB
Boous exercises
Write a class Roman that:
●
Given an integer number returns its roman
numeral
Write a class Gray that:
●
Given a binary number, with fixed length
(known at init) returns its Gray
representation
●
Gray code:
http://mathworld.wolfram.com/GrayCode.html
Luca Cerina, R.A. @ NECSTLab – DEIB
Class ioheritaoce
• A class can may be created starting from another class
already existing and more generic
• The new class inherits all the attributes and functions defined
in the parent class
• Inheritance is used to specialize a class with respect to a
generic one
• In order to inherit from a parent class, the syntax is:
class childClass(parentClass):
Luca Cerina, R.A. @ NECSTLab – DEIB
Example
Class the child inherits from
pass is used to avoid to stpecify
the imtplementaton of a class,
functon, if etc.
Luca Cerina, R.A. @ NECSTLab – DEIB
Overridiog
• Overriding is used to redefine, within a child class, functions
already defined by the parent class, in order to make them
more specify for the child class
• To apply overriding, it is enough to redefine a function using
the same name
• Usually overriding is applied to __init__ constructor function
Luca Cerina, R.A. @ NECSTLab – DEIB
Example
Overriding of __init__
functon
Functon priotVal only belongs
to childClass, it cannot be called
by tparentClass
Luca Cerina, R.A. @ NECSTLab – DEIB
Exercise 12: class ioheritaoce
●
Given the class Rectangle, inherit a class
Rombus that calculates its area and
perimeter accordingly (define PI inside the
class or use Numpy)
Luca Cerina, R.A. @ NECSTLab – DEIB
Files
• Python provides many functionalities to act on files
• In particular, it allows to:
• Open,
• Read,
• Write,
• Close a file
• I/O functions documentation is available here:
https://docs.python.org/3/tutorial/inputoutput.html
Luca Cerina, R.A. @ NECSTLab – DEIB
Files: opeo aod close
• Open file
f = open(filename, mode)
• Close file f.close()
File name Otpen modes:
‘r’: reading
‘w’: writng(it deletes the tprevious content)
‘x’: creates a new file to write it
‘a’: atptpend
‘b’: binary mode
‘t’: textual mode
‘+’: otpen a file to utpdate it
Luca Cerina, R.A. @ NECSTLab – DEIB
Files: read aod write
• Read file
out = f.read(size)
out = f.readline()
• Write file
f.write(stringa)
Reads size characters
If omited, it reads to the
end of file
Reads a file row
Writes a string on the file
Therefore, it is necessary to convert
data into strings to write them
Luca Cerina, R.A. @ NECSTLab – DEIB
Files: seek aod tell
• Current position on file
out = f.tell()
• Change position on file
f.seek(offset, from_where)
Returns the current tpositon inside
the file
Ofset: character ofset with
restpect to a reference tpoint
From_where: reference tpoint
Se 0: file beginning (default value)
Se 1: current tpositon
Se 2: file end
Luca Cerina, R.A. @ NECSTLab – DEIB
Numpy
• NumPy is the abbreviation of Numerical Python: it is a Python
extension mainly thought for scientific computation
• NumPy allows to use (in addition to other things):
• Multidimensional arrays in a easier way with respect to Python
• Mathematical functions (linear algebra, random numbers, …)
• To use NumPy, it is necessary to import its module:
• Documentation: http://docs.scipy.org/doc/
Luca Cerina, R.A. @ NECSTLab – DEIB
odarray
• ndarray is a NumPy data type that allows to create n-dimensional
arrays
• The easiest way to create a NumPy array is array function:
array(object, dtype=None, copy=1, order=None)
Parameters already set to a default value
It is not necessary to insert them unless their values have to be changed
Luca Cerina, R.A. @ NECSTLab – DEIB
odarray
• ndarray is a NumPy data type that allows to create n-dimensional
arrays
• The easiest way to create a NumPy array is array function:
array(object, dtype=None, copy=1, order=None)
Parameters already set to a default value
It is not necessary to insert them unless their values have to be changed
Luca Cerina, R.A. @ NECSTLab – DEIB
odarray
array(object, dtype=None, copy=1, order=None)
• object: the object the array has to be created from (list, tuple,
etc.)
• dtype: the array data type (bool, int, float, complex, etc.)
• copy: indicates whether the array is created through a copy of
the object
• order: memory allocation style (C or Fortran)
Luca Cerina, R.A. @ NECSTLab – DEIB
odarray atributes
• shape: array shape
!! pure monodimensional arrays have shape (N, )
not (N, 1)
• ndim: array dimensions number
monodimensional arrays have ndim = 1
• itemsize: byte dimension of each element
• strides: bytes to jump to obtain the next element
for a specific dimension
Luca Cerina, R.A. @ NECSTLab – DEIB
Other creatoo methods
• zeros( shape, dtype=float, order =‘C’ )
• ones( shape, dtype=None, order =‘C’ )
• empty( shape, dtype=None, order =‘C’ )
Luca Cerina, R.A. @ NECSTLab – DEIB
Other creatoo methods
• identity( n, dtype=None )
• eye( N, M=None, k=0, dtype=float )
• k indicates how much to translate the main diagonal
• k > 0: diagonal translated k positions right
• k < 0: diagonal translated k positions left
Luca Cerina, R.A. @ NECSTLab – DEIB
Araoge aod liospace
• Just like a list may be created from range, it is possible to create an
array with two similar functions: arange and linspace
• arange is very similar to range:
arange( [start,] stop[, step,], dtype=None )
• linspace generates a sequence of num values equally distributed
from start to stop
linspace( start, stop, num=50, endpoint=True, restep=False )
• endpoint: if True, stop is the last value
• restep: if True, the function returns also the step
optional Diferently from range(), float
stetps are accetpted
Luca Cerina, R.A. @ NECSTLab – DEIB
Reshape aod resize
• Reshape and resize functions allow to change
the shape of the array and resize it
reshape(shape)
• Reshape creates/returns a new data structure
redistributing array elements (the number of
elements does not change)
!!Not an inplace function
resize(new_shape)
• Resize works in-place modifying the array
itself
Luca Cerina, R.A. @ NECSTLab – DEIB
Exercise 13: array creatoo
Write a Python program that, given in input a bidimensional shape,
creates:
• A sequence of values coherent with that dimension
• A monodimensional array starting from the sequence
• A bidimensional array whose shape corresponts to the one
inserted by the user
• Example:
• Shape = (2,3)
• Sequence = 0, 1, 2, 3, 4, 5
• Monodimensional_array = [0, 1, 2, 3, 4, 5]
• Bidimensional_array = [[0, 1, 2], [3, 4, 5]]
Luca Cerina, R.A. @ NECSTLab – DEIB
Array sliciog
• It is possible to access to portions of a list and/or array
through slicing operator “:”
Array[start:end]
• start: index of the first element to start from
– It may be omitted if equal to 0
• end: index of the last element to arrive
– The element is not included in slicing output
– It may be omitted if it correspond to the array end
Luca Cerina, R.A. @ NECSTLab – DEIB
Array sliciog
• It is possible to apply slicing also on multidimensional arrays
(but not on lists!!)
array[startDIM1:endDIM1, startDIM2:endDIM2, etc.]
00 11 22 33 44 55
66 77 88 99 1010 1111
1212 1313 1414 1515 1616 1717
Luca Cerina, R.A. @ NECSTLab – DEIB
Array operators
Array / scalar operations: array / array operations:
a e b must have the same dimensions!!
Luca Cerina, R.A. @ NECSTLab – DEIB
Comparisoo operators
Luca Cerina, R.A. @ NECSTLab – DEIB
Matplotlib
• Matplotlib library provides functionalities to plot 2D graphs using
functions similar to MATLAB
• matplotlib contains different sub-modules, in particular we will refer
to pyplot
• Documentation: http://matplotlib.org/
Stpecial Jutpyter directve to
show gratphs within the working
area
Imtport namestpace
mattplotlib.tpytplot as “tplt”
Examtple of a tpytplot functon
to create a gratphShow gratph
Luca Cerina, R.A. @ NECSTLab – DEIB
Create a graph
• To create a graph, define a set of values to be drawn with plot
and then visualize the graph with show
• plot function may be called in different ways
plot(y_values_list)
plot(x_values_list, y_values_list)
plot(x_values_list, y_values_list, line_properties)
NOTE: lists may be substituted by NumPy arrays
Luca Cerina, R.A. @ NECSTLab – DEIB
example
X axis values are
automatcally defined in
an incremental order
startng from 0
Luca Cerina, R.A. @ NECSTLab – DEIB
example
Y values list
X values list
Note: the dimensions of the
two lists must coincide!
Luca Cerina, R.A. @ NECSTLab – DEIB
Multple lioe graphs
By calling multiple times plot function, it is possible to insert more
curves inside the same graph
Luca Cerina, R.A. @ NECSTLab – DEIB
Set graph propertes
Luca Cerina, R.A. @ NECSTLab – DEIB
Exercise 14:
Write a Python program that, given a frequency and a certain time
window (e.g. 2,10 s):
●
Create a sinusoid at given frequency in the time window and plot it
●
Create a sinusoid with a frequency 10% higher
●
Sum the two sinusoids and plot it in another figure.
●
Observe the phenomen ;) (hint: acoustic battimento)

More Related Content

What's hot

VLSI Fresher Resume
VLSI Fresher ResumeVLSI Fresher Resume
VLSI Fresher Resumevikas kumar
 
20221226_TITECH_lecture_ishizaki_public.pdf
20221226_TITECH_lecture_ishizaki_public.pdf20221226_TITECH_lecture_ishizaki_public.pdf
20221226_TITECH_lecture_ishizaki_public.pdfKazuaki Ishizaki
 
Introduction to Arduino & Raspberry Pi
Introduction to Arduino & Raspberry PiIntroduction to Arduino & Raspberry Pi
Introduction to Arduino & Raspberry PiAhmad Hafeezi
 
NIOS II Processor.ppt
NIOS II Processor.pptNIOS II Processor.ppt
NIOS II Processor.pptAtef46
 
The Evolution of Java
The Evolution of JavaThe Evolution of Java
The Evolution of JavaFu Cheng
 
System verilog control flow
System verilog control flowSystem verilog control flow
System verilog control flowPushpa Yakkala
 
Introduction to System verilog
Introduction to System verilog Introduction to System verilog
Introduction to System verilog Pushpa Yakkala
 
できる!並列・並行プログラミング
できる!並列・並行プログラミングできる!並列・並行プログラミング
できる!並列・並行プログラミングPreferred Networks
 
Introduction to char device driver
Introduction to char device driverIntroduction to char device driver
Introduction to char device driverVandana Salve
 
SoC based smartphone processors
SoC based smartphone processorsSoC based smartphone processors
SoC based smartphone processorsAnkush Kumar
 
DPDK & Layer 4 Packet Processing
DPDK & Layer 4 Packet ProcessingDPDK & Layer 4 Packet Processing
DPDK & Layer 4 Packet ProcessingMichelle Holley
 
Clock gating
Clock gatingClock gating
Clock gatingMahi
 
Pythonで作る俺様サウンドエフェクター
Pythonで作る俺様サウンドエフェクターPythonで作る俺様サウンドエフェクター
Pythonで作る俺様サウンドエフェクターRansui Iso
 
Embedded system - Introduction to interfacing with peripherals
Embedded system - Introduction to interfacing with peripheralsEmbedded system - Introduction to interfacing with peripherals
Embedded system - Introduction to interfacing with peripheralsVibrant Technologies & Computers
 
Software hardware co-design using xilinx zynq soc
Software hardware co-design using xilinx zynq socSoftware hardware co-design using xilinx zynq soc
Software hardware co-design using xilinx zynq socHossam Hassan
 

What's hot (20)

VLSI Fresher Resume
VLSI Fresher ResumeVLSI Fresher Resume
VLSI Fresher Resume
 
Introduction to OpenCL
Introduction to OpenCLIntroduction to OpenCL
Introduction to OpenCL
 
20221226_TITECH_lecture_ishizaki_public.pdf
20221226_TITECH_lecture_ishizaki_public.pdf20221226_TITECH_lecture_ishizaki_public.pdf
20221226_TITECH_lecture_ishizaki_public.pdf
 
Introduction to Arduino & Raspberry Pi
Introduction to Arduino & Raspberry PiIntroduction to Arduino & Raspberry Pi
Introduction to Arduino & Raspberry Pi
 
NIOS II Processor.ppt
NIOS II Processor.pptNIOS II Processor.ppt
NIOS II Processor.ppt
 
The Evolution of Java
The Evolution of JavaThe Evolution of Java
The Evolution of Java
 
Vlsi design flow
Vlsi design flowVlsi design flow
Vlsi design flow
 
System verilog control flow
System verilog control flowSystem verilog control flow
System verilog control flow
 
Introduction to System verilog
Introduction to System verilog Introduction to System verilog
Introduction to System verilog
 
できる!並列・並行プログラミング
できる!並列・並行プログラミングできる!並列・並行プログラミング
できる!並列・並行プログラミング
 
Introduction to char device driver
Introduction to char device driverIntroduction to char device driver
Introduction to char device driver
 
Présentation FPGA
Présentation FPGAPrésentation FPGA
Présentation FPGA
 
SoC based smartphone processors
SoC based smartphone processorsSoC based smartphone processors
SoC based smartphone processors
 
DPDK & Layer 4 Packet Processing
DPDK & Layer 4 Packet ProcessingDPDK & Layer 4 Packet Processing
DPDK & Layer 4 Packet Processing
 
Clock gating
Clock gatingClock gating
Clock gating
 
Pythonで作る俺様サウンドエフェクター
Pythonで作る俺様サウンドエフェクターPythonで作る俺様サウンドエフェクター
Pythonで作る俺様サウンドエフェクター
 
Linux-Internals-and-Networking
Linux-Internals-and-NetworkingLinux-Internals-and-Networking
Linux-Internals-and-Networking
 
Embedded system - Introduction to interfacing with peripherals
Embedded system - Introduction to interfacing with peripheralsEmbedded system - Introduction to interfacing with peripherals
Embedded system - Introduction to interfacing with peripherals
 
Software hardware co-design using xilinx zynq soc
Software hardware co-design using xilinx zynq socSoftware hardware co-design using xilinx zynq soc
Software hardware co-design using xilinx zynq soc
 
FPGA In a Nutshell
FPGA In a NutshellFPGA In a Nutshell
FPGA In a Nutshell
 

Similar to PYNQ Platform and Python Lesson

Python indroduction
Python indroductionPython indroduction
Python indroductionFEG
 
Programming with Python: Week 1
Programming with Python: Week 1Programming with Python: Week 1
Programming with Python: Week 1Ahmet Bulut
 
Python and Pytorch tutorial and walkthrough
Python and Pytorch tutorial and walkthroughPython and Pytorch tutorial and walkthrough
Python and Pytorch tutorial and walkthroughgabriellekuruvilla
 
summer training report on python
summer training report on pythonsummer training report on python
summer training report on pythonShubham Yadav
 
Python (3).pdf
Python (3).pdfPython (3).pdf
Python (3).pdfsamiwaris2
 
Travis Oliphant "Python for Speed, Scale, and Science"
Travis Oliphant "Python for Speed, Scale, and Science"Travis Oliphant "Python for Speed, Scale, and Science"
Travis Oliphant "Python for Speed, Scale, and Science"Fwdays
 
Q-Step_WS_02102019_Practical_introduction_to_Python.pptx
Q-Step_WS_02102019_Practical_introduction_to_Python.pptxQ-Step_WS_02102019_Practical_introduction_to_Python.pptx
Q-Step_WS_02102019_Practical_introduction_to_Python.pptxnyomans1
 
Q-SPractical_introduction_to_Python.pptx
Q-SPractical_introduction_to_Python.pptxQ-SPractical_introduction_to_Python.pptx
Q-SPractical_introduction_to_Python.pptxJeromeTacata3
 
Q-Step_WS_02102019_Practical_introduction_to_Python.pdf
Q-Step_WS_02102019_Practical_introduction_to_Python.pdfQ-Step_WS_02102019_Practical_introduction_to_Python.pdf
Q-Step_WS_02102019_Practical_introduction_to_Python.pdfMichpice
 
Tutorial on-python-programming
Tutorial on-python-programmingTutorial on-python-programming
Tutorial on-python-programmingChetan Giridhar
 
Python interview questions and answers
Python interview questions and answersPython interview questions and answers
Python interview questions and answerskavinilavuG
 
web programming UNIT VIII python by Bhavsingh Maloth
web programming UNIT VIII python by Bhavsingh Malothweb programming UNIT VIII python by Bhavsingh Maloth
web programming UNIT VIII python by Bhavsingh MalothBhavsingh Maloth
 
Python interview questions and answers
Python interview questions and answersPython interview questions and answers
Python interview questions and answersRojaPriya
 
prakash ppt (2).pdf
prakash ppt (2).pdfprakash ppt (2).pdf
prakash ppt (2).pdfShivamKS4
 
Python presentation of Government Engineering College Aurangabad, Bihar
Python presentation of Government Engineering College Aurangabad, BiharPython presentation of Government Engineering College Aurangabad, Bihar
Python presentation of Government Engineering College Aurangabad, BiharUttamKumar617567
 
Using SWIG to Control, Prototype, and Debug C Programs with Python
Using SWIG to Control, Prototype, and Debug C Programs with PythonUsing SWIG to Control, Prototype, and Debug C Programs with Python
Using SWIG to Control, Prototype, and Debug C Programs with PythonDavid Beazley (Dabeaz LLC)
 
4. python functions
4. python   functions4. python   functions
4. python functionsin4400
 

Similar to PYNQ Platform and Python Lesson (20)

Python indroduction
Python indroductionPython indroduction
Python indroduction
 
Python Demo.pptx
Python Demo.pptxPython Demo.pptx
Python Demo.pptx
 
Python Demo.pptx
Python Demo.pptxPython Demo.pptx
Python Demo.pptx
 
Programming with Python: Week 1
Programming with Python: Week 1Programming with Python: Week 1
Programming with Python: Week 1
 
Python and Pytorch tutorial and walkthrough
Python and Pytorch tutorial and walkthroughPython and Pytorch tutorial and walkthrough
Python and Pytorch tutorial and walkthrough
 
summer training report on python
summer training report on pythonsummer training report on python
summer training report on python
 
Python (3).pdf
Python (3).pdfPython (3).pdf
Python (3).pdf
 
Travis Oliphant "Python for Speed, Scale, and Science"
Travis Oliphant "Python for Speed, Scale, and Science"Travis Oliphant "Python for Speed, Scale, and Science"
Travis Oliphant "Python for Speed, Scale, and Science"
 
Q-Step_WS_02102019_Practical_introduction_to_Python.pptx
Q-Step_WS_02102019_Practical_introduction_to_Python.pptxQ-Step_WS_02102019_Practical_introduction_to_Python.pptx
Q-Step_WS_02102019_Practical_introduction_to_Python.pptx
 
Q-SPractical_introduction_to_Python.pptx
Q-SPractical_introduction_to_Python.pptxQ-SPractical_introduction_to_Python.pptx
Q-SPractical_introduction_to_Python.pptx
 
Q-Step_WS_02102019_Practical_introduction_to_Python.pdf
Q-Step_WS_02102019_Practical_introduction_to_Python.pdfQ-Step_WS_02102019_Practical_introduction_to_Python.pdf
Q-Step_WS_02102019_Practical_introduction_to_Python.pdf
 
Python intro
Python introPython intro
Python intro
 
Tutorial on-python-programming
Tutorial on-python-programmingTutorial on-python-programming
Tutorial on-python-programming
 
Python interview questions and answers
Python interview questions and answersPython interview questions and answers
Python interview questions and answers
 
web programming UNIT VIII python by Bhavsingh Maloth
web programming UNIT VIII python by Bhavsingh Malothweb programming UNIT VIII python by Bhavsingh Maloth
web programming UNIT VIII python by Bhavsingh Maloth
 
Python interview questions and answers
Python interview questions and answersPython interview questions and answers
Python interview questions and answers
 
prakash ppt (2).pdf
prakash ppt (2).pdfprakash ppt (2).pdf
prakash ppt (2).pdf
 
Python presentation of Government Engineering College Aurangabad, Bihar
Python presentation of Government Engineering College Aurangabad, BiharPython presentation of Government Engineering College Aurangabad, Bihar
Python presentation of Government Engineering College Aurangabad, Bihar
 
Using SWIG to Control, Prototype, and Debug C Programs with Python
Using SWIG to Control, Prototype, and Debug C Programs with PythonUsing SWIG to Control, Prototype, and Debug C Programs with Python
Using SWIG to Control, Prototype, and Debug C Programs with Python
 
4. python functions
4. python   functions4. python   functions
4. python functions
 

More from NECST Lab @ Politecnico di Milano

Embedding based knowledge graph link prediction for drug repurposing
Embedding based knowledge graph link prediction for drug repurposingEmbedding based knowledge graph link prediction for drug repurposing
Embedding based knowledge graph link prediction for drug repurposingNECST Lab @ Politecnico di Milano
 
PLASTER - PYNQ-based abandoned object detection using a map-reduce approach o...
PLASTER - PYNQ-based abandoned object detection using a map-reduce approach o...PLASTER - PYNQ-based abandoned object detection using a map-reduce approach o...
PLASTER - PYNQ-based abandoned object detection using a map-reduce approach o...NECST Lab @ Politecnico di Milano
 
EMPhASIS - An EMbedded Public Attention Stress Identification System
 EMPhASIS - An EMbedded Public Attention Stress Identification System EMPhASIS - An EMbedded Public Attention Stress Identification System
EMPhASIS - An EMbedded Public Attention Stress Identification SystemNECST Lab @ Politecnico di Milano
 
Maeve - Fast genome analysis leveraging exact string matching
Maeve - Fast genome analysis leveraging exact string matchingMaeve - Fast genome analysis leveraging exact string matching
Maeve - Fast genome analysis leveraging exact string matchingNECST Lab @ Politecnico di Milano
 

More from NECST Lab @ Politecnico di Milano (20)

Mesticheria Team - WiiReflex
Mesticheria Team - WiiReflexMesticheria Team - WiiReflex
Mesticheria Team - WiiReflex
 
Punto e virgola Team - Stressometro
Punto e virgola Team - StressometroPunto e virgola Team - Stressometro
Punto e virgola Team - Stressometro
 
BitIt Team - Stay.straight
BitIt Team - Stay.straight BitIt Team - Stay.straight
BitIt Team - Stay.straight
 
BabYodini Team - Talking Gloves
BabYodini Team - Talking GlovesBabYodini Team - Talking Gloves
BabYodini Team - Talking Gloves
 
printf("Nome Squadra"); Team - NeoTon
printf("Nome Squadra"); Team - NeoTonprintf("Nome Squadra"); Team - NeoTon
printf("Nome Squadra"); Team - NeoTon
 
BlackBoard Team - Motion Tracking Platform
BlackBoard Team - Motion Tracking PlatformBlackBoard Team - Motion Tracking Platform
BlackBoard Team - Motion Tracking Platform
 
#include<brain.h> Team - HomeBeatHome
#include<brain.h> Team - HomeBeatHome#include<brain.h> Team - HomeBeatHome
#include<brain.h> Team - HomeBeatHome
 
Flipflops Team - Wave U
Flipflops Team - Wave UFlipflops Team - Wave U
Flipflops Team - Wave U
 
Bug(atta) Team - Little Brother
Bug(atta) Team - Little BrotherBug(atta) Team - Little Brother
Bug(atta) Team - Little Brother
 
#NECSTCamp: come partecipare
#NECSTCamp: come partecipare#NECSTCamp: come partecipare
#NECSTCamp: come partecipare
 
NECSTCamp101@2020.10.1
NECSTCamp101@2020.10.1NECSTCamp101@2020.10.1
NECSTCamp101@2020.10.1
 
NECSTLab101 2020.2021
NECSTLab101 2020.2021NECSTLab101 2020.2021
NECSTLab101 2020.2021
 
TreeHouse, nourish your community
TreeHouse, nourish your communityTreeHouse, nourish your community
TreeHouse, nourish your community
 
TiReX: Tiled Regular eXpressionsmatching architecture
TiReX: Tiled Regular eXpressionsmatching architectureTiReX: Tiled Regular eXpressionsmatching architecture
TiReX: Tiled Regular eXpressionsmatching architecture
 
Embedding based knowledge graph link prediction for drug repurposing
Embedding based knowledge graph link prediction for drug repurposingEmbedding based knowledge graph link prediction for drug repurposing
Embedding based knowledge graph link prediction for drug repurposing
 
PLASTER - PYNQ-based abandoned object detection using a map-reduce approach o...
PLASTER - PYNQ-based abandoned object detection using a map-reduce approach o...PLASTER - PYNQ-based abandoned object detection using a map-reduce approach o...
PLASTER - PYNQ-based abandoned object detection using a map-reduce approach o...
 
EMPhASIS - An EMbedded Public Attention Stress Identification System
 EMPhASIS - An EMbedded Public Attention Stress Identification System EMPhASIS - An EMbedded Public Attention Stress Identification System
EMPhASIS - An EMbedded Public Attention Stress Identification System
 
Luns - Automatic lungs segmentation through neural network
Luns - Automatic lungs segmentation through neural networkLuns - Automatic lungs segmentation through neural network
Luns - Automatic lungs segmentation through neural network
 
BlastFunction: How to combine Serverless and FPGAs
BlastFunction: How to combine Serverless and FPGAsBlastFunction: How to combine Serverless and FPGAs
BlastFunction: How to combine Serverless and FPGAs
 
Maeve - Fast genome analysis leveraging exact string matching
Maeve - Fast genome analysis leveraging exact string matchingMaeve - Fast genome analysis leveraging exact string matching
Maeve - Fast genome analysis leveraging exact string matching
 

Recently uploaded

Concurrency Control in Database Management system
Concurrency Control in Database Management systemConcurrency Control in Database Management system
Concurrency Control in Database Management systemChristalin Nelson
 
Virtual-Orientation-on-the-Administration-of-NATG12-NATG6-and-ELLNA.pdf
Virtual-Orientation-on-the-Administration-of-NATG12-NATG6-and-ELLNA.pdfVirtual-Orientation-on-the-Administration-of-NATG12-NATG6-and-ELLNA.pdf
Virtual-Orientation-on-the-Administration-of-NATG12-NATG6-and-ELLNA.pdfErwinPantujan2
 
Grade 9 Quarter 4 Dll Grade 9 Quarter 4 DLL.pdf
Grade 9 Quarter 4 Dll Grade 9 Quarter 4 DLL.pdfGrade 9 Quarter 4 Dll Grade 9 Quarter 4 DLL.pdf
Grade 9 Quarter 4 Dll Grade 9 Quarter 4 DLL.pdfJemuel Francisco
 
AUDIENCE THEORY -CULTIVATION THEORY - GERBNER.pptx
AUDIENCE THEORY -CULTIVATION THEORY -  GERBNER.pptxAUDIENCE THEORY -CULTIVATION THEORY -  GERBNER.pptx
AUDIENCE THEORY -CULTIVATION THEORY - GERBNER.pptxiammrhaywood
 
How to Add Barcode on PDF Report in Odoo 17
How to Add Barcode on PDF Report in Odoo 17How to Add Barcode on PDF Report in Odoo 17
How to Add Barcode on PDF Report in Odoo 17Celine George
 
INTRODUCTION TO CATHOLIC CHRISTOLOGY.pptx
INTRODUCTION TO CATHOLIC CHRISTOLOGY.pptxINTRODUCTION TO CATHOLIC CHRISTOLOGY.pptx
INTRODUCTION TO CATHOLIC CHRISTOLOGY.pptxHumphrey A Beña
 
Q4-PPT-Music9_Lesson-1-Romantic-Opera.pptx
Q4-PPT-Music9_Lesson-1-Romantic-Opera.pptxQ4-PPT-Music9_Lesson-1-Romantic-Opera.pptx
Q4-PPT-Music9_Lesson-1-Romantic-Opera.pptxlancelewisportillo
 
ROLES IN A STAGE PRODUCTION in arts.pptx
ROLES IN A STAGE PRODUCTION in arts.pptxROLES IN A STAGE PRODUCTION in arts.pptx
ROLES IN A STAGE PRODUCTION in arts.pptxVanesaIglesias10
 
Daily Lesson Plan in Mathematics Quarter 4
Daily Lesson Plan in Mathematics Quarter 4Daily Lesson Plan in Mathematics Quarter 4
Daily Lesson Plan in Mathematics Quarter 4JOYLYNSAMANIEGO
 
4.18.24 Movement Legacies, Reflection, and Review.pptx
4.18.24 Movement Legacies, Reflection, and Review.pptx4.18.24 Movement Legacies, Reflection, and Review.pptx
4.18.24 Movement Legacies, Reflection, and Review.pptxmary850239
 
Integumentary System SMP B. Pharm Sem I.ppt
Integumentary System SMP B. Pharm Sem I.pptIntegumentary System SMP B. Pharm Sem I.ppt
Integumentary System SMP B. Pharm Sem I.pptshraddhaparab530
 
EMBODO Lesson Plan Grade 9 Law of Sines.docx
EMBODO Lesson Plan Grade 9 Law of Sines.docxEMBODO Lesson Plan Grade 9 Law of Sines.docx
EMBODO Lesson Plan Grade 9 Law of Sines.docxElton John Embodo
 
HỌC TỐT TIẾNG ANH 11 THEO CHƯƠNG TRÌNH GLOBAL SUCCESS ĐÁP ÁN CHI TIẾT - CẢ NĂ...
HỌC TỐT TIẾNG ANH 11 THEO CHƯƠNG TRÌNH GLOBAL SUCCESS ĐÁP ÁN CHI TIẾT - CẢ NĂ...HỌC TỐT TIẾNG ANH 11 THEO CHƯƠNG TRÌNH GLOBAL SUCCESS ĐÁP ÁN CHI TIẾT - CẢ NĂ...
HỌC TỐT TIẾNG ANH 11 THEO CHƯƠNG TRÌNH GLOBAL SUCCESS ĐÁP ÁN CHI TIẾT - CẢ NĂ...Nguyen Thanh Tu Collection
 
Field Attribute Index Feature in Odoo 17
Field Attribute Index Feature in Odoo 17Field Attribute Index Feature in Odoo 17
Field Attribute Index Feature in Odoo 17Celine George
 
Millenials and Fillennials (Ethical Challenge and Responses).pptx
Millenials and Fillennials (Ethical Challenge and Responses).pptxMillenials and Fillennials (Ethical Challenge and Responses).pptx
Millenials and Fillennials (Ethical Challenge and Responses).pptxJanEmmanBrigoli
 
GRADE 4 - SUMMATIVE TEST QUARTER 4 ALL SUBJECTS
GRADE 4 - SUMMATIVE TEST QUARTER 4 ALL SUBJECTSGRADE 4 - SUMMATIVE TEST QUARTER 4 ALL SUBJECTS
GRADE 4 - SUMMATIVE TEST QUARTER 4 ALL SUBJECTSJoshuaGantuangco2
 
Expanded definition: technical and operational
Expanded definition: technical and operationalExpanded definition: technical and operational
Expanded definition: technical and operationalssuser3e220a
 
Activity 2-unit 2-update 2024. English translation
Activity 2-unit 2-update 2024. English translationActivity 2-unit 2-update 2024. English translation
Activity 2-unit 2-update 2024. English translationRosabel UA
 
ENG 5 Q4 WEEk 1 DAY 1 Restate sentences heard in one’s own words. Use appropr...
ENG 5 Q4 WEEk 1 DAY 1 Restate sentences heard in one’s own words. Use appropr...ENG 5 Q4 WEEk 1 DAY 1 Restate sentences heard in one’s own words. Use appropr...
ENG 5 Q4 WEEk 1 DAY 1 Restate sentences heard in one’s own words. Use appropr...JojoEDelaCruz
 

Recently uploaded (20)

Concurrency Control in Database Management system
Concurrency Control in Database Management systemConcurrency Control in Database Management system
Concurrency Control in Database Management system
 
Virtual-Orientation-on-the-Administration-of-NATG12-NATG6-and-ELLNA.pdf
Virtual-Orientation-on-the-Administration-of-NATG12-NATG6-and-ELLNA.pdfVirtual-Orientation-on-the-Administration-of-NATG12-NATG6-and-ELLNA.pdf
Virtual-Orientation-on-the-Administration-of-NATG12-NATG6-and-ELLNA.pdf
 
Grade 9 Quarter 4 Dll Grade 9 Quarter 4 DLL.pdf
Grade 9 Quarter 4 Dll Grade 9 Quarter 4 DLL.pdfGrade 9 Quarter 4 Dll Grade 9 Quarter 4 DLL.pdf
Grade 9 Quarter 4 Dll Grade 9 Quarter 4 DLL.pdf
 
AUDIENCE THEORY -CULTIVATION THEORY - GERBNER.pptx
AUDIENCE THEORY -CULTIVATION THEORY -  GERBNER.pptxAUDIENCE THEORY -CULTIVATION THEORY -  GERBNER.pptx
AUDIENCE THEORY -CULTIVATION THEORY - GERBNER.pptx
 
How to Add Barcode on PDF Report in Odoo 17
How to Add Barcode on PDF Report in Odoo 17How to Add Barcode on PDF Report in Odoo 17
How to Add Barcode on PDF Report in Odoo 17
 
INTRODUCTION TO CATHOLIC CHRISTOLOGY.pptx
INTRODUCTION TO CATHOLIC CHRISTOLOGY.pptxINTRODUCTION TO CATHOLIC CHRISTOLOGY.pptx
INTRODUCTION TO CATHOLIC CHRISTOLOGY.pptx
 
Q4-PPT-Music9_Lesson-1-Romantic-Opera.pptx
Q4-PPT-Music9_Lesson-1-Romantic-Opera.pptxQ4-PPT-Music9_Lesson-1-Romantic-Opera.pptx
Q4-PPT-Music9_Lesson-1-Romantic-Opera.pptx
 
Paradigm shift in nursing research by RS MEHTA
Paradigm shift in nursing research by RS MEHTAParadigm shift in nursing research by RS MEHTA
Paradigm shift in nursing research by RS MEHTA
 
ROLES IN A STAGE PRODUCTION in arts.pptx
ROLES IN A STAGE PRODUCTION in arts.pptxROLES IN A STAGE PRODUCTION in arts.pptx
ROLES IN A STAGE PRODUCTION in arts.pptx
 
Daily Lesson Plan in Mathematics Quarter 4
Daily Lesson Plan in Mathematics Quarter 4Daily Lesson Plan in Mathematics Quarter 4
Daily Lesson Plan in Mathematics Quarter 4
 
4.18.24 Movement Legacies, Reflection, and Review.pptx
4.18.24 Movement Legacies, Reflection, and Review.pptx4.18.24 Movement Legacies, Reflection, and Review.pptx
4.18.24 Movement Legacies, Reflection, and Review.pptx
 
Integumentary System SMP B. Pharm Sem I.ppt
Integumentary System SMP B. Pharm Sem I.pptIntegumentary System SMP B. Pharm Sem I.ppt
Integumentary System SMP B. Pharm Sem I.ppt
 
EMBODO Lesson Plan Grade 9 Law of Sines.docx
EMBODO Lesson Plan Grade 9 Law of Sines.docxEMBODO Lesson Plan Grade 9 Law of Sines.docx
EMBODO Lesson Plan Grade 9 Law of Sines.docx
 
HỌC TỐT TIẾNG ANH 11 THEO CHƯƠNG TRÌNH GLOBAL SUCCESS ĐÁP ÁN CHI TIẾT - CẢ NĂ...
HỌC TỐT TIẾNG ANH 11 THEO CHƯƠNG TRÌNH GLOBAL SUCCESS ĐÁP ÁN CHI TIẾT - CẢ NĂ...HỌC TỐT TIẾNG ANH 11 THEO CHƯƠNG TRÌNH GLOBAL SUCCESS ĐÁP ÁN CHI TIẾT - CẢ NĂ...
HỌC TỐT TIẾNG ANH 11 THEO CHƯƠNG TRÌNH GLOBAL SUCCESS ĐÁP ÁN CHI TIẾT - CẢ NĂ...
 
Field Attribute Index Feature in Odoo 17
Field Attribute Index Feature in Odoo 17Field Attribute Index Feature in Odoo 17
Field Attribute Index Feature in Odoo 17
 
Millenials and Fillennials (Ethical Challenge and Responses).pptx
Millenials and Fillennials (Ethical Challenge and Responses).pptxMillenials and Fillennials (Ethical Challenge and Responses).pptx
Millenials and Fillennials (Ethical Challenge and Responses).pptx
 
GRADE 4 - SUMMATIVE TEST QUARTER 4 ALL SUBJECTS
GRADE 4 - SUMMATIVE TEST QUARTER 4 ALL SUBJECTSGRADE 4 - SUMMATIVE TEST QUARTER 4 ALL SUBJECTS
GRADE 4 - SUMMATIVE TEST QUARTER 4 ALL SUBJECTS
 
Expanded definition: technical and operational
Expanded definition: technical and operationalExpanded definition: technical and operational
Expanded definition: technical and operational
 
Activity 2-unit 2-update 2024. English translation
Activity 2-unit 2-update 2024. English translationActivity 2-unit 2-update 2024. English translation
Activity 2-unit 2-update 2024. English translation
 
ENG 5 Q4 WEEk 1 DAY 1 Restate sentences heard in one’s own words. Use appropr...
ENG 5 Q4 WEEk 1 DAY 1 Restate sentences heard in one’s own words. Use appropr...ENG 5 Q4 WEEk 1 DAY 1 Restate sentences heard in one’s own words. Use appropr...
ENG 5 Q4 WEEk 1 DAY 1 Restate sentences heard in one’s own words. Use appropr...
 

PYNQ Platform and Python Lesson

  • 1. Firma convenzione Politecnico di Milano e Veneranda Fabbrica del Duomo di Milano Aula Magna – Rettorato Mercoledì 27 maggio 2015 Lesson 1: Introduction to PYNQ Platform and Python language Luca Cerina – luca.cerina@polimi.it Ver. Updated – 22/11/2017
  • 2. Luca Cerina, R.A. @ NECSTLab – DEIB PYNQ Board • 650Mhz dual-core Cortex-A9 processor • 512MB DDR3 • FPGA: ZYNQ XC7Z020-1CLG400C Per maggiori informazioni: http://www.tpynq.io/home.html
  • 3. Luca Cerina, R.A. @ NECSTLab – DEIB PYNQ Board 3 Communicaton over ethernet Jutpyter serverJutpyter server Pynq APIPynq API FPGA: programmabile logic ARM Processor PMODHDMI (out, in) Audio connectors GPIO: leds, butoos, switches Ethernet Overlay (base.bit) Overlay (base.bit) USB Micro SD (Linux OS + Jutpyter notebook) Pyoq Board
  • 4. Luca Cerina, R.A. @ NECSTLab – DEIB FPGA: Field Programmable Gate Arrays A fully retprogrammable chitp in which diferent basic blocks, like Look-Utp-Tables, Memory, and Flitp-Flotps internally connects together to recreate comtplex digital circuits.
  • 5. Luca Cerina, R.A. @ NECSTLab – DEIB THE COMMUNITY FUNNEL Atptplicaton develotpers Driver develotpers Overlay designers ● Python on jutpyter ● Everything else ● Vivado SDK ● C/C++ ● Python wratptpers ● Vivado/SDSoC suite ● C/C++, VHDL
  • 6. Luca Cerina, R.A. @ NECSTLab – DEIB Hardware ioterfaces Pynq provides: • 2 Fully programmable PMOD connectors • 1 Arduino compatible interface • 1 HDMI and audio I/O
  • 7. Luca Cerina, R.A. @ NECSTLab – DEIB Hardware ioterfaces
  • 8. Luca Cerina, R.A. @ NECSTLab – DEIB LED, Butoos aod switches Pynq provides: • 6 LED commanded from Python (2 RGB) • 2 Switches and 4 Buttons with readable state
  • 9. Luca Cerina, R.A. @ NECSTLab – DEIB WHAT IS AN OVERLAY Overlays are “hardware libraries” that extends the Processing System with a Programmable Logic design
  • 10. Luca Cerina, R.A. @ NECSTLab – DEIB WHAT IS JUPYTER Project Jupyter is an open source project was born out of the IPython Project in 2014 as it evolved to support interactive data science and scientific computing across all programming languages. Jupyter will always be 100% open source software, free for all to use and released under the liberal terms of the modified BSD license
  • 11. Luca Cerina, R.A. @ NECSTLab – DEIB WHAT IS PYTHON • Python is a tprogramming language • High level • Intertpreted • (weak) Dynamic Tytping • Object-oriented We’ll get more on this later • Useful for fast tprototytping of atptplicatons and with code readability in mind. • Documentaton: https://www.tpython.org/doc/
  • 12. Luca Cerina, R.A. @ NECSTLab – DEIB SUGGESTED DEVELOPMENT PLATFORM
  • 13. Luca Cerina, R.A. @ NECSTLab – DEIB C vs PYTHON C - Low level - Comtpiled - Strong tytping - Non object-oriented Pythoo - High level - Intertpreted - Weak tytping - Object-oriented
  • 14. Luca Cerina, R.A. @ NECSTLab – DEIB C vs PYTHON C - Low level - Comtpiled - Strong tytping - Non object-oriented Pythoo - High level - Intertpreted - Weak tytping - Object-oriented Extplicit memory allocaton (tpointers management) Imtplicit memory allocaton (hidden to the user)
  • 15. Luca Cerina, R.A. @ NECSTLab – DEIB C vs PYTHON C - Low level - Comtpiled - Strong tytping - Non object-oriented Pythoo - High level - Intertpreted - Weak tytping - Object-oriented file.cfile.c gccgcc Machine codeMachine code file.tpyfile.tpy Python intertpreterPython intertpreter Intertpreted codeIntertpreted code
  • 16. Luca Cerina, R.A. @ NECSTLab – DEIB C vs PYTHON C - Low level - Comtpiled - Strong tytping - Non object-oriented Pythoo - High level - Intertpreted - Weak tytping - Object-oriented int a; a = 5; //Correct a = “string”; //Error!! a = 5 #Correct a = “stringa” #Correct a = 1.3 #Correct Type must be known by the compiler No explicit type declaration
  • 17. Luca Cerina, R.A. @ NECSTLab – DEIB C vs PYTHON C - Low level - Comtpiled - Strong tytping - Non object-oriented Pythoo - High level - Intertpreted - Weak tytping - Object-oriented void sort(int * array){...} ... int vet[] = {1, 6, 4, 8, 9}; sort(vet); vet = [1, 6, 4, 8, 9] vet.sort() sort is a functon of the object vet and act on it
  • 18. Luca Cerina, R.A. @ NECSTLab – DEIB Pythoo syotax • Variables do not need declaraton before usage • ‘;’ are not necessary to end an instructon line, • INDENTATION IS FUNDAMENTAL • Code constructs (if-else, for lootps, etc…) use ‘:’ + indentaton instead of ‘{‘ Indentaton is done with Tabs or Whitestpaces • Comments are # (single line) or “”” (multline/docstring) • INDENTATION IS FUNDAMENTAL
  • 19. Luca Cerina, R.A. @ NECSTLab – DEIB Exercise 0: Hello world (agaio) print(“Hello world!”) No need for I/O library imtport
  • 20. Luca Cerina, R.A. @ NECSTLab – DEIB Exercise 1: I/O ● Read a number from command line, and print if it is odd or even ● Read a number from command line, add 5 to it, and then save it in another variable as a string. Then print it (hints int() and str() functions)
  • 21. Luca Cerina, R.A. @ NECSTLab – DEIB Pythoo libraries • As in C, it is possible to load libraries (modules) to extend python functionalities • Modules can be imported in various ways: imtport os #imtport namestpace of module os imtport os as O #imtport namestpace of module os with an alias O from os imtport * #imtport the entre namestpace from os imtport curdir as CC from os imtport listdir as LS #imtport a stpecific element of the module os.curdir os.listdir(“Desktotp”) O.curdir O.listdir(“Desktotp”) curdir listdir(“Desktotp”) CC LS(“Desktotp”)
  • 22. Luca Cerina, R.A. @ NECSTLab – DEIB Libraries examples • OS → operative system calls (e.g. cd, ls, shell functions) • Numpy → exhaustive numerical library
  • 23. Luca Cerina, R.A. @ NECSTLab – DEIB Utlites • help(obj) shows the object documentaton (atributes, functons, behaviour, …) • len(obj) returns the length of the object Not all objects have a length! • dir(obj) list all atributes and functons of obj • tytpe(obj) returns the tytpe of the object
  • 24. Luca Cerina, R.A. @ NECSTLab – DEIB Exercise 2: I/O “type” check ● Read anything from command line, and verify (print) if the object is numeric, alphanumeric or alphabetic ● Read anything from command line, and if it is alphanumeric, print it in uppercase
  • 25. Luca Cerina, R.A. @ NECSTLab – DEIB Pythoo basic types tpi esempio int 1, 2, 3 float 1.5, 2.2, 4.3 bool True, False str “abc”, “string” list [1, 2, 3, 4], [”abc”, “def”, “ghi”] dict {key1: value1, key2: value2} tutple (1, 2, 3, 4), (“abc”, “def”, “ghi”) set {1, 2, 3, 4}, {“abc”, “def”, “ghi”} List, dict, tutple and sets will be extplained later
  • 26. Luca Cerina, R.A. @ NECSTLab – DEIB Logical operators Operaziooi C Pythoo And logico && and Or logico || or Not logico ! not Uguaglianza ==, != ==, !=, is, is not Confronto <, >, <=, >= <, >, <=, >= ==, != verify if two objects have the same value is, is not verify if two objects are the same object
  • 27. Luca Cerina, R.A. @ NECSTLab – DEIB If-else coostruct • If-else basic structure (REMEMBER INDENTATION): • Nested if-else constructs can be grouped using elif: elif
  • 28. Luca Cerina, R.A. @ NECSTLab – DEIB Exercise 3: Calculator ● Read two numbers (let’s assume them to be float) ● Ask the user the type of calculation to be done ● Execute it and print the result ● Bonus! Allow the user to insert complex numbers (X+Yj, hint: numpy)
  • 29. Luca Cerina, R.A. @ NECSTLab – DEIB While loop • While loop syntax is identical to the C equivalent: • Con! Python do not provide a do..while loop • But! It is possible to insert a else branch at the exit of the while loop • The else branch is executed when the while condition becomes False
  • 30. Luca Cerina, R.A. @ NECSTLab – DEIB Exercise 4: Maximum value ● Let the user insert a certain number of positive integers (NB check the type!) ● Ask the user to continue the insertion of to stop the loop ● At the end of the loop print the maximum value inserted
  • 31. Luca Cerina, R.A. @ NECSTLab – DEIB For loop • For loop is different from the C equivalent • A variable iterates on the elements of a sequence • A sequence can be a lot of things: • A list, dictionary or set • A string • An iterator • Also the for loop supports else branch on exit
  • 32. Luca Cerina, R.A. @ NECSTLab – DEIB Iterators • Iterators are objects that return a sequence of other objects one element at a time using the method next() • The classical iterator in the for loop is range() • Fine parameter is mandatory, inizio and step are optional: • Iteration goes from inizio to fine (excluded) • Default ‘inizio’ is 0 • Default ‘step’ is 1 • ‘Step’ requires that ‘inizio’ is inserted • If inizio > fine the loop is not executed, unless step is < 0
  • 33. Luca Cerina, R.A. @ NECSTLab – DEIB Exercise 5: Expooeotal ● Read one base and one exponent (integer and positive) and print the exponential. ● Use both ‘**’ python operator and a for loop
  • 34. Luca Cerina, R.A. @ NECSTLab – DEIB Exercise 6: PI calculatoo The PI value can be approximated as: The integral value is calculated as sum of rectangles. The higher the number of rectangles, the better the approximation. Write a Python script that ask the number of intervals to the user, calculate the PI value and calculate the error against the one available in the numpy library (use the abs() function to obtain the error)
  • 35. Luca Cerina, R.A. @ NECSTLab – DEIB Lists • Lists are object, with variable dimension, that contains other objects in the order they were inserted • Lists can contain objects of diferent tytpe (bags of objects) • Python-like lists do not exist in C, but C lists allow size extension C - Arrays cannot contain diferent tytpes - Arrays cannot change their size Python - Lists can contain diferent objects - A list can change its dimension
  • 36. Luca Cerina, R.A. @ NECSTLab – DEIB Lists creatoo • A list can be created using: • Otperator [ ] • Functon list() … REMEMBER C reserved names • Otperator [ ] • [ ] create an emtpty list • [val1, val2, val3] create a list startng from inserted values • Functon list() • list() create an emtpty list • list(iteratore) create a list using the iterator elements
  • 37. Luca Cerina, R.A. @ NECSTLab – DEIB Read aod iosert elemeots • Read lista[index] like in C, index represents the position of the elements (0- start counting) • Insertion • append(val) insert the element val at the end of the list • insert(index, val) insert an element in the position index
  • 38. Luca Cerina, R.A. @ NECSTLab – DEIB Remove elemeots • Removal • Pop(index) remove the element index • remove(val) remove the first occurrence of val
  • 39. Luca Cerina, R.A. @ NECSTLab – DEIB Traverse the elemeots • To traverse a list we can use a for-loop like in C • Or you can iterate directly on the list • In this case i is the value of every element in the list
  • 40. Luca Cerina, R.A. @ NECSTLab – DEIB Exercise 7: list maoagemeot ● Write a program that given a list of integer numbers, print the list in reverse order ● Modify the program to save the reversed list into another list object, then print it ● Bonus! Do it without using a loop (hint lookup the list functions)
  • 41. Luca Cerina, R.A. @ NECSTLab – DEIB Exercise 7: possible solutoos ● Lists allow negative indexing ● The function reverse() on the list revert the object itself. Attention! Reverse is an in-place function and directly modify the object instead of returning another one
  • 42. Luca Cerina, R.A. @ NECSTLab – DEIB List coocateoatoo • You can merge or concatenate two lists using operator + • It is possible to replicate a list N times using the multiplication operator
  • 43. Luca Cerina, R.A. @ NECSTLab – DEIB Lists of Lists • A list can be defined inside another list • To access an element inside you have to access the first level list, and then the element inside it
  • 44. Luca Cerina, R.A. @ NECSTLab – DEIB Lists of Lists • Python matrices can be defined as a list of lists • The outer list contains the rows of the matrix, the inner ones the elements of the columns related to that row • Examtples of matrix creatons • It is tpossible to create “matrices” with rows of diferent lengths
  • 45. Luca Cerina, R.A. @ NECSTLab – DEIB List compreheosioo • List comtprehension is a method that allows to build list in a fast and comtpressed manner • A list is created startng from the descritpton writen inside [ ] • x indicate the value that we want to insert in the list • The value inserted can be the result of an otperaton, or if conditons
  • 46. Luca Cerina, R.A. @ NECSTLab – DEIB Teroary operator • This list comtprehension relies on a ternary otperator, i.e. an otperator that returns a certain value based on a conditon being true or false • If cooditoo is true, the outtput of this istructon is value cood_true, otherwise it is value cood_false
  • 47. Luca Cerina, R.A. @ NECSTLab – DEIB Exercise 8: list compreheosioo ● Write a program that given integer N, creates a matrix with all odd numbers in a row, and all even numbers in the second row ● Given two dice, one with N faces, one with M faces, generate all the possible combinations (hint: it’s a list of tuples) ● Given a list of integers, generate a new list with only the elements > than the average
  • 48. Luca Cerina, R.A. @ NECSTLab – DEIB Exercise 8: solutoo ● Combs = [(x,y) for x in range(1,N+1) for y in range(1, M+1)] ● Input = [1,2,3,4,5,6,7,8,9,10] average = sum(Input)/len(Input) Output = [x for x in Input if x>average]
  • 49. Luca Cerina, R.A. @ NECSTLab – DEIB Fuoctoos • Functons are reusable tportons of tprogram, which can be called when necessary • A Pythoo functon can receive 0 or more parameters and generate 0 or more outputs • Diference between Python and C functons • WITH GREAT POWER COMES GREAT RESPONSIBILITY!!! C - Functons can return at most one result - It is necessary to declare the tytpe of both tparameters and result - If necessary, it is tpossible to define the functon tprototytpe Python - Functons can return more results - It is not necessary to declare the tytpe of either tparameters or result - Functons are defined/redefined dynamically: no tprototytpes
  • 50. Luca Cerina, R.A. @ NECSTLab – DEIB Defoitoo aod call • To define a functon use the keyword def followed by the functon name and its intput names (tpay atenton to the ending “:” and code indentaton!): • A functon call is executed stpecifying the functon name followed by the tpossible intputs • NOTE: at the moment of a functon call, the functon has to be defined
  • 51. Luca Cerina, R.A. @ NECSTLab – DEIB Parameters • Let us distnguish between tparameter tpassage with immutable and mutable types • Immutable tytpes are tpassed by copy to the functons: • The functon receives a cotpy of the tparameters • Changes to the tparameters will not be seen outside the functon • Mutable tytpes are tpassed by refereoce to the functons: • The functon receives the reference to the tparameters (like for C arrays) • Changes to the tparameters are seen outside the functon Immutable types Mutable types int list float dict bool set str tutple
  • 52. Luca Cerina, R.A. @ NECSTLab – DEIB Returo values To return a result, it is necessary to use the keyword returo setparatng the returned values with a comma
  • 53. Luca Cerina, R.A. @ NECSTLab – DEIB Exercise 9: fuoctoos ● Write a function that sums all the elements in a list ● Write a function that calculates the factorial of a number ● Rewrite the integral program (lesson 1) into a function, and return both integral value and error to the user
  • 54. Luca Cerina, R.A. @ NECSTLab – DEIB Dictooaries • Python dictonaries are a very tpowerful tool that allows to organize data as <key, value> coutples • Given a key, it is tpossible to ask the dictonary to tprovide the related value (if it exists) • Key must be an immutable tytpe (int, float, str, …) while the value may assume any tytpe • Dictonaries are commonly used to store data associatons: • Given the first and last name of a tperson (key), retrieve his/her tphone number (value of iot type) • Given a class name (key), retrieve the list of teachers who have taught that class (value of list type) • Given a city name (key), retrieve the tphone book of that city inhabitants (value of dictooary type)
  • 55. Luca Cerina, R.A. @ NECSTLab – DEIB Dictooary creatoo • A dictonary may be created in two ways: • {} otperator • Functon dict() • Examtples of creaton with {} otperator • Examtples of creaton with functon dict()
  • 56. Luca Cerina, R.A. @ NECSTLab – DEIB Add, modify, remove • To add an element to a dictonary or edit an already existng one, use square brackets: • To remove an element from a dictonary startng from its key, use pop(key):
  • 57. Luca Cerina, R.A. @ NECSTLab – DEIB Access elemeots • The number of elements in a dictonary can be obtained using leo(dictooary) • To read the value correstponding to a key use square brackets • To verify whether a key exists or not, use the io otperator: • Dictonary keys are iterable!
  • 58. Luca Cerina, R.A. @ NECSTLab – DEIB Classes • Classes are data structures whose purpose is to contain different types of variables and functions useful to provide functionalities related to the kind of data to be represented • Differently from C struct, classes may also contain functions • An instance of a class is called object C Python Declaraton of variables or functons
  • 59. Luca Cerina, R.A. @ NECSTLab – DEIB Namespace • When a class (or a function) is created, the declared variables/functions lay within the space of names (namespace) generated for that class/function • The namespace is a mapping from names to objects (like a dictionary) that allows to invoke both the attributes and functions defined within that namespace • For instance, when the Python interpreter starts, some functions are already available inside the initial namespace, like print() • Is it possible to add functions/attributes and other namespaces to a namespace through import command
  • 60. Luca Cerina, R.A. @ NECSTLab – DEIB Scopes • The scope is a textual region of a Python program where it is possible to directly invoke attributes/functions of a namespace • Attributes/functions of a class can be directly called only within the class itself, while, from the outside, it is necessary to use an object of the class to call them (through “.” operator) • Within a scope, it is also possible to redefine attributes/functions defined in outer scopes
  • 61. Luca Cerina, R.A. @ NECSTLab – DEIB Scope example global var var redefined by test_scope Through global, test_scotpe edits var
  • 62. Luca Cerina, R.A. @ NECSTLab – DEIB Class defoitoo • In order to define a class, the keyword class is required: class className: • Within the class definition, it is possible to declare attributes and functions self tparameter is a reference to the class itself from within the class Object creaton self has not to be tpassed as argument when invoking class functons
  • 63. Luca Cerina, R.A. @ NECSTLab – DEIB Class defoitoo with __ioit__ • It is possible to define within a class a special function called __init__ whose purpose is to initialize class attributes during its creation • The attributes have not to be previously declared i, a and b were not declared yet The values of a and b have to be tpassed during object creaton
  • 64. Luca Cerina, R.A. @ NECSTLab – DEIB Exercise 11: class creatoo ● Write a class rectangle with two attributes (one per side) ● Define a function that returns the rectangle’s area ● Define a function that returns the rectangle’s perimeter
  • 65. Luca Cerina, R.A. @ NECSTLab – DEIB Boous exercises Write a class Roman that: ● Given an integer number returns its roman numeral Write a class Gray that: ● Given a binary number, with fixed length (known at init) returns its Gray representation ● Gray code: http://mathworld.wolfram.com/GrayCode.html
  • 66. Luca Cerina, R.A. @ NECSTLab – DEIB Class ioheritaoce • A class can may be created starting from another class already existing and more generic • The new class inherits all the attributes and functions defined in the parent class • Inheritance is used to specialize a class with respect to a generic one • In order to inherit from a parent class, the syntax is: class childClass(parentClass):
  • 67. Luca Cerina, R.A. @ NECSTLab – DEIB Example Class the child inherits from pass is used to avoid to stpecify the imtplementaton of a class, functon, if etc.
  • 68. Luca Cerina, R.A. @ NECSTLab – DEIB Overridiog • Overriding is used to redefine, within a child class, functions already defined by the parent class, in order to make them more specify for the child class • To apply overriding, it is enough to redefine a function using the same name • Usually overriding is applied to __init__ constructor function
  • 69. Luca Cerina, R.A. @ NECSTLab – DEIB Example Overriding of __init__ functon Functon priotVal only belongs to childClass, it cannot be called by tparentClass
  • 70. Luca Cerina, R.A. @ NECSTLab – DEIB Exercise 12: class ioheritaoce ● Given the class Rectangle, inherit a class Rombus that calculates its area and perimeter accordingly (define PI inside the class or use Numpy)
  • 71. Luca Cerina, R.A. @ NECSTLab – DEIB Files • Python provides many functionalities to act on files • In particular, it allows to: • Open, • Read, • Write, • Close a file • I/O functions documentation is available here: https://docs.python.org/3/tutorial/inputoutput.html
  • 72. Luca Cerina, R.A. @ NECSTLab – DEIB Files: opeo aod close • Open file f = open(filename, mode) • Close file f.close() File name Otpen modes: ‘r’: reading ‘w’: writng(it deletes the tprevious content) ‘x’: creates a new file to write it ‘a’: atptpend ‘b’: binary mode ‘t’: textual mode ‘+’: otpen a file to utpdate it
  • 73. Luca Cerina, R.A. @ NECSTLab – DEIB Files: read aod write • Read file out = f.read(size) out = f.readline() • Write file f.write(stringa) Reads size characters If omited, it reads to the end of file Reads a file row Writes a string on the file Therefore, it is necessary to convert data into strings to write them
  • 74. Luca Cerina, R.A. @ NECSTLab – DEIB Files: seek aod tell • Current position on file out = f.tell() • Change position on file f.seek(offset, from_where) Returns the current tpositon inside the file Ofset: character ofset with restpect to a reference tpoint From_where: reference tpoint Se 0: file beginning (default value) Se 1: current tpositon Se 2: file end
  • 75. Luca Cerina, R.A. @ NECSTLab – DEIB Numpy • NumPy is the abbreviation of Numerical Python: it is a Python extension mainly thought for scientific computation • NumPy allows to use (in addition to other things): • Multidimensional arrays in a easier way with respect to Python • Mathematical functions (linear algebra, random numbers, …) • To use NumPy, it is necessary to import its module: • Documentation: http://docs.scipy.org/doc/
  • 76. Luca Cerina, R.A. @ NECSTLab – DEIB odarray • ndarray is a NumPy data type that allows to create n-dimensional arrays • The easiest way to create a NumPy array is array function: array(object, dtype=None, copy=1, order=None) Parameters already set to a default value It is not necessary to insert them unless their values have to be changed
  • 77. Luca Cerina, R.A. @ NECSTLab – DEIB odarray • ndarray is a NumPy data type that allows to create n-dimensional arrays • The easiest way to create a NumPy array is array function: array(object, dtype=None, copy=1, order=None) Parameters already set to a default value It is not necessary to insert them unless their values have to be changed
  • 78. Luca Cerina, R.A. @ NECSTLab – DEIB odarray array(object, dtype=None, copy=1, order=None) • object: the object the array has to be created from (list, tuple, etc.) • dtype: the array data type (bool, int, float, complex, etc.) • copy: indicates whether the array is created through a copy of the object • order: memory allocation style (C or Fortran)
  • 79. Luca Cerina, R.A. @ NECSTLab – DEIB odarray atributes • shape: array shape !! pure monodimensional arrays have shape (N, ) not (N, 1) • ndim: array dimensions number monodimensional arrays have ndim = 1 • itemsize: byte dimension of each element • strides: bytes to jump to obtain the next element for a specific dimension
  • 80. Luca Cerina, R.A. @ NECSTLab – DEIB Other creatoo methods • zeros( shape, dtype=float, order =‘C’ ) • ones( shape, dtype=None, order =‘C’ ) • empty( shape, dtype=None, order =‘C’ )
  • 81. Luca Cerina, R.A. @ NECSTLab – DEIB Other creatoo methods • identity( n, dtype=None ) • eye( N, M=None, k=0, dtype=float ) • k indicates how much to translate the main diagonal • k > 0: diagonal translated k positions right • k < 0: diagonal translated k positions left
  • 82. Luca Cerina, R.A. @ NECSTLab – DEIB Araoge aod liospace • Just like a list may be created from range, it is possible to create an array with two similar functions: arange and linspace • arange is very similar to range: arange( [start,] stop[, step,], dtype=None ) • linspace generates a sequence of num values equally distributed from start to stop linspace( start, stop, num=50, endpoint=True, restep=False ) • endpoint: if True, stop is the last value • restep: if True, the function returns also the step optional Diferently from range(), float stetps are accetpted
  • 83. Luca Cerina, R.A. @ NECSTLab – DEIB Reshape aod resize • Reshape and resize functions allow to change the shape of the array and resize it reshape(shape) • Reshape creates/returns a new data structure redistributing array elements (the number of elements does not change) !!Not an inplace function resize(new_shape) • Resize works in-place modifying the array itself
  • 84. Luca Cerina, R.A. @ NECSTLab – DEIB Exercise 13: array creatoo Write a Python program that, given in input a bidimensional shape, creates: • A sequence of values coherent with that dimension • A monodimensional array starting from the sequence • A bidimensional array whose shape corresponts to the one inserted by the user • Example: • Shape = (2,3) • Sequence = 0, 1, 2, 3, 4, 5 • Monodimensional_array = [0, 1, 2, 3, 4, 5] • Bidimensional_array = [[0, 1, 2], [3, 4, 5]]
  • 85. Luca Cerina, R.A. @ NECSTLab – DEIB Array sliciog • It is possible to access to portions of a list and/or array through slicing operator “:” Array[start:end] • start: index of the first element to start from – It may be omitted if equal to 0 • end: index of the last element to arrive – The element is not included in slicing output – It may be omitted if it correspond to the array end
  • 86. Luca Cerina, R.A. @ NECSTLab – DEIB Array sliciog • It is possible to apply slicing also on multidimensional arrays (but not on lists!!) array[startDIM1:endDIM1, startDIM2:endDIM2, etc.] 00 11 22 33 44 55 66 77 88 99 1010 1111 1212 1313 1414 1515 1616 1717
  • 87. Luca Cerina, R.A. @ NECSTLab – DEIB Array operators Array / scalar operations: array / array operations: a e b must have the same dimensions!!
  • 88. Luca Cerina, R.A. @ NECSTLab – DEIB Comparisoo operators
  • 89. Luca Cerina, R.A. @ NECSTLab – DEIB Matplotlib • Matplotlib library provides functionalities to plot 2D graphs using functions similar to MATLAB • matplotlib contains different sub-modules, in particular we will refer to pyplot • Documentation: http://matplotlib.org/ Stpecial Jutpyter directve to show gratphs within the working area Imtport namestpace mattplotlib.tpytplot as “tplt” Examtple of a tpytplot functon to create a gratphShow gratph
  • 90. Luca Cerina, R.A. @ NECSTLab – DEIB Create a graph • To create a graph, define a set of values to be drawn with plot and then visualize the graph with show • plot function may be called in different ways plot(y_values_list) plot(x_values_list, y_values_list) plot(x_values_list, y_values_list, line_properties) NOTE: lists may be substituted by NumPy arrays
  • 91. Luca Cerina, R.A. @ NECSTLab – DEIB example X axis values are automatcally defined in an incremental order startng from 0
  • 92. Luca Cerina, R.A. @ NECSTLab – DEIB example Y values list X values list Note: the dimensions of the two lists must coincide!
  • 93. Luca Cerina, R.A. @ NECSTLab – DEIB Multple lioe graphs By calling multiple times plot function, it is possible to insert more curves inside the same graph
  • 94. Luca Cerina, R.A. @ NECSTLab – DEIB Set graph propertes
  • 95. Luca Cerina, R.A. @ NECSTLab – DEIB Exercise 14: Write a Python program that, given a frequency and a certain time window (e.g. 2,10 s): ● Create a sinusoid at given frequency in the time window and plot it ● Create a sinusoid with a frequency 10% higher ● Sum the two sinusoids and plot it in another figure. ● Observe the phenomen ;) (hint: acoustic battimento)