Index
●
Compiler vs Interpreter
●
Intro Python
●
Variables and (re)assignment
●
(essential) Data types: number
●
Math Formula Translation
Intro Python
Interpreters and compilers
● To be able to execute high-level language instructions on
the underlying physical machine, there are two
possibilities:
– Interpretation (interpreter), which uses a program
called an interpreter that can directly execute the high-
level instructions
– Translation (compiler), which first translates the
sequence of high-level instructions into a
corresponding sequence of instructions on the
physical machine using a program called a compiler
Compiled languages
(C, C++, Haskell, Rust, Go, ...)
Text Editor
CPU-readable
●
To run our code, we must:
1) Compile the source code to run on specific
hardware, generating a binary "executable"
2) Execute the binary code: the instructions are read
from the binary file and sent directly to the processor
●
Advantages: Since the program is already translated
and optimized for specific hardware, execution is
usually faster!
●
Disadvantages: Limited number of machines and
operating systems on which it can run!
Compilation phase
●
Many errors are visible during compilation
my_script.exe
[Link]
Interpreted languages
(Python, JavaScript, Java, PHP, ...)
●
The interpreter can directly read and execute Text Editor
instructions from the source code
●
The instructions are first interpreted at runtime and then
sent to the processor
●
Disadvantages: usually slower execution, because the
source code (or bytecode, if present) must be
translated into binary code on the fly.
●
Advantages: can run on any machine with a (Python)
virtual machine
●
Faster development cycle (write, test, and run)
●
Compile errors visible only when the code is run
(unless the editor shows them to you) python my_script.py
Code Execution in Python
Interpreter: you need a program that reads and
executes individual Python statements or
scripts!
●
Official: [Link]
●
Web interface:
➢ [Link]
demo_compiler
➢ [Link]
●
Editor + cmd: Notepad++ + conda cmd
●
Integrated Development Environment (IDE):
provides interpreter, editor, windows for
execution, debug, ecc.
➢
Thonny: [Link]
Why Python
●
Easy to learn, makes you very productive in a short
time (less is more)
●
Large community, lots of online material for further
study
●
Among the most “wanted” languages in industry
●
Cross-platform and open source (>36 years)
●
Very extensive standard library and has many
ready-to-use libraries!
●
Fields: Web, data science, machine learning,
scripting, teaching, games, hardware, etc.
●
It also has some flaws, of course...
[Link]
Why Python
●
Easily extendable to other languages
●
Call matlab from python
●
Call python from matlab
[Link]
Code Execution in Python
ipython: advanced version of the python REPL
1) Interactive Shell: But running "python" is fine!
– Each individual statement is written to the shell
and executed after the [RETURN] key.
– Interactive REPL (Read-Eval-Print Loop)
interface
– You can write Python expressions that are
executed directly
2) Script:
– The sequence of statements is written to a text
file and executed
– File with .py extension.
– You need an editor for writing the file
– Note: No .pyc files to manipulate!
Exercise
● Try adding two numbers!
Web interface:
[Link]
emo_compiler
[Link]
Variables and (re)assignment
Variables and assignment
● A variable is used to remember a useful result data encoding
01100001
– We are reserving a memory area associated
with a name (label) int str
97 “a”
– The name is used to access the reserved
memory, to read and modify its value
● Data type: data encoding + permitted operations
variable = expression
How I’m reading this
I'm assigning 123 (type → integer) to the variable pippo
[Link] 12
Variables and assignment
Pippo
Variable assignment Black Board / RAM Memory
variable = expression
123
1)We ask Python to solve the expression on
the right of the equals sign
2)We reserve some memory space
3)We fill the memory with the result of the
expression
4)We create a label that points to the memory
13
Variables and assignment
variable = expression
Question:
what do they
have in
common?
Answer: the ‘=’
Variables and (re)assignment
Pippo
Variable assignment Black Board / RAM Memory
variable = expression
123
456
Question: what happen if I
execute the second line on code?
Answer: I’m creating a new
variable!
15
Garbage Collection
Pippo
Variable assignment Black Board / RAM Memory
variable = expression
123
456
Question: what happen to the old used memory?
Answer:
The memory area containing 123 is no longer accessible!
Because there is no longer a label pointing to that memory area!
16
Garbage Collection
Pippo
Variable assignment Black Board / RAM Memory
variable = expression
123
456
Question: what happen to the old used memory?
Answer:
In Python, there is a background process called Garbage Collector
that takes care of freeing up unused memory.
17
Assignment Vs Comparison
Variable assignment equality operator
variable = expression expression1 == expression2
1)We ask Python to solve the expression 1)We ask Python to solve expression 1
on the right of the equals sign and expression 2.
2)We reserve some memory space 2)We compare the results of the two
3)We fill the memory with the result of the expressions to see if they are equal
expression 3)Python returns the result of the
4)We create a label that points to the comparison (True or False), because
memory it is an expression itself.
18
Equality operator
area == (base * altezza)
expression1 expression2
What happened there?
1)Expression 1 resolves to 35 because the area
variable was previously initialized to that value
2)Expression 2 resolves to 35 because result of
multiplication of two variable
3)Since 35 on the left is equal to 35 on the right,
the output is True
Rules for variable names
● Regole per creare un nome di variabile:
● Rules for creating a variable name:
– Can contain uppercase or lowercase letters [A-
z], digits [0-9], or the underscore _
– Cannot begin with a digit [0-9]
– Cannot be the same as Python keywords
– Case sensitive: uppercase and lowercase
letters are different (var != Var)
[Link]
Esercizio
Which of these are valid names?
radius 2example pippo_64
_fuu import prize 6
my@email Variable !ls
Esercizio
Which of these are valid names?
radius 2example pippo_64
_fuu import prize 6
my@email Variable !ls
keyword python
Question:
could you find where we defined a variable?
Question:
could you find where we defined a variable?
Lines legend
input / output
1) decision / cycle
operation
2)
3)
4)
5)
6)
7)
8)
9)
10)
Exercise: Let's swap the values of two variables
●
Swap the values of two variables using a temporary variable
●
Initialize variables a and b with the values 5 and 10
●
Use a temporary variable temp to swap the two values
a b
Black Board / RAM Memory
5 10
Let's try to do it together!
25
Exercise: Let's swap the values of two variables
a b
Black Board / RAM Memory
10
5 10
Quanto valeva “a” ???
26
Exercise: Let's swap the values of two variables
●
Swap the values of two variables using a temporary variable
●
Initialize variables a and b with the values 5 and 10
●
Use a temporary variable temp to swap the two values
Exercise: Let's swap the values of two variables
If I use the temp variable instead:
a b
Black Board / RAM Memory
10
5 10
5
temp
28
Exercise: Let's swap the values of two variables
It should hold for any value of
a and b.. let's try!
Exercise: Let's swap the values of two variables
If I use the temp variable instead:
a b
Black Board / RAM Memory
“hello”
10 “hello”
10
“hello”
temp
30
(essential) Data types: number
Data types
● Data types: set of admitted values + permitted operations
Testo str
Numero int float complex
Sequenza list tuple range
Mappa chiave/valore dict OrderedDict
Set set frozenset
Booleano bool
Binario bytes bytearray memoryview
None NoneType
Note: If we need something more advanced, Python
allows us to define the data types we want!
Encoding & Operations
data encoding
01100001
Same bits on memory can
be interpreted in different
int str
way depending on the type
97 “a”
For each data type are defined different operations
Data Type Conversion (casting)
How to find the data type?
→ Use the type(data) utility function!
How do I convert one data type to another?
→ Use the data type name
Conversione di tipo (casting)
WARNING!
Implicit
● It can sometimes be useful to convert the
type. conversion!
– Example: I need to concatenate an
integer value to a string to print.
● Sometimes it happens automatically!
– Example: integer division
Explicit
conversion!
Data type: number
Number: integer Number: float (decimal)
Keyword: int Keyword: float
Characteristic: number without comma! Characteristic: number with comma!
Casting: Casting:
36
Tipo di dato: numero
Number: int Number: float
Basic operations: addition (+), subtraction (-), multiplication (*), division (/)
Extra operations: integer division (//), rest (%), power (**)
number1 operator number2
addition subtraction multiplication
integer division rest power 43
division
vs
37
Rounding schemes
Python rounds to the lowest integer by default
This is the only way to round a number ??? No!
Rounding schemes
If you need to round a number using a different
criterion:
●
round: to the nearest integer 3.14 → 3 2.718 → 3
●
floor: the next lower signed integer 3.14 → 3 2.718 → 2
●
ceil: the next higher signed integer 3.14 → 4 2.718 → 3
Math Formula Translation
Exercise
● Convert from degrees Celsius to degrees Fahrenheit
Imagine that it is now 12°C
What if I wanted to generalize (for any temperature)? I need variables!
Formula Translation
How we can implement this expression?
1)Be sure that every variable is defined!
2)Identify all operations involved
3)Convert each operator in “python ops”!
Program Execution
Execution loop
FETCH Let's try to become
the automatic
executors of the
algorithm we
execute!
EXEC DECODE
43
Formula Translation & Execution!
● Convert the following formula to Python code Black Board / RAM Memory
step1 = 10 + 7 = 17
step2 = 172 = 289
step3 = 5 – 2 = 3
step4 = 289 * 3 = 867
step5 = 867 / 3 = 289.0
Where to start?
step6 = 12 / 14 = 0.8571428571428571
Dividi et impera: divide the problem into many subproblems... step7 = 289.0 + 0.8571428571428571 =
289.85714285714283
output = 24352974.895043727
44
Representation with flow algorithms
● Convert the following formula to Python code
Where to start?
Dividi et impera: divide the problem into many subproblems...
45
How to convert a formula into code
● Convert the following formula to Python code Black Board / RAM Memory
Where to start?
Dividi et impera: divide the problem into many subproblems...
output = num / div!
46
How to convert a formula into code
● Convert the following formula to Python code Black Board / RAM Memory
step1 = 10 + 7 – 3 = 14
step2 = 142 = 196
step3 = 52 = 25
Where to start? step4 = 25 - 2 = 23
step5 = 234 = 279841
Dividi et impera: divide the problem into many subproblems... output = 196 /279841
output = num / div!
47
Exercise
● Convert the following formula to Python code Black Board / RAM Memory
Where to start?
Dividi et impera: divide the problem into many subproblems...
Exercise: Describe the various steps of
the algorithm to solve the formula on
paper.
Use flowcharts!
48
Exercise
● Convert the following formula to Python code Black Board / RAM Memory
step1 = 10 + 7 = 17
step2 = 172 = 289
step3 = 3 * 5 = 15
step4 = 289 - 15 = 274
step5 = 2 - 12 = -10
Where to start?
step6 = 274 / (-10) = -27.4
Dividi et impera: divide the problem into many subproblems... step7 = 14 / 20 = 0.7
output = -27.4 + 0.7 = -26.4
49
Algorithm and Process
Black Board / RAM Memory
●
An algorithm is a precise (but abstract) sequence of
elementary steps step1 = 10 + 7 = 17
➢
The only memory used is that needed to store the step2 = 172 = 289
source code. step3 = 3 * 5 = 15
●
A process is the execution of the algorithm on real data step4 = 289 - 15 = 274
➢
Memory is needed to store input data (a, b, c, etc.), step5 = 2 - 12 = -10
intermediate data (step 1, step 2, etc.), and output step6 = 274 / (-10) = -27.4
data (output) step7 = 14 / 20 = 0.7
output = -27.4 + 0.7 = -26.4
50
Esercizio
● Convert the following formula to Python code Black Board / RAM Memory
Exercise: Follow the
instructions on paper
and fill your memory as
Where to start?
seen previously!
Dividi et impera: divide the problem into many subproblems...
Exercise: Describe on paper the
various steps of the algorithm to solve
the formula
Do it at home!
51