

























































































Studia grazie alle numerose risorse presenti su Docsity
Guadagna punti aiutando altri studenti oppure acquistali con un piano Premium
Questa pagina non è visibile nell’anteprima
Non perderti parti importanti!


























































































à DEF: A coding language represents the language used to communicate with a machine
In particular, a coding language is a formal communication artefact (a more or less direct communication act) to the
machine, a representation under the form of an executable algorithm (executable by means of the machine)
o Being formal consist of being “correct, complete and non ambiguous”
In other words, the coding language, is a form of ab-straction, a process by means of which a concept/fact/object
is described in a correct, complete and non-ambiguous way in its properties and actions to the aim of solving a
problem about the entity described. The machine is like a stupid guy that doesn’t have the capability of interpreting
what you are saying to him, so you have to be super clear.
o Coding languages were conceived at different level of abstraction (assembly, Fortran, Lisp, Cobol, Basic, Pascal,
Prolog, SmallTalk, C, C++, Java, C#, Perl, Python, Php, Ruby, Javascript...)
The Notions of Intension, Extension and Expressive Power of a code
à Intension is related to the power of synthesis
à Extension is related to the expressive power of the single instruction
Example 1
Low intenstion = more power of synthesis
High extension = more expressive power
The word “Animal” à this single word has got a broad meaning because it includes a great variety of property and
objects. (potere di sintesi proprio perchè una singola parola sintetizza e fa riferimento a un grande gruppo di oggetti
e proprietà)
The code “ create” has got low intension and high extension à as you can see from the slides, it includes specific
implicit subfunctions.
Example 2
High intension = less power of synthesis
Low Extension = less expressive power
The word “persian cat” has got a narrow and specific meaning. The power of synthesis is very low because it refers
to a specific category, so it doesn’t summarize a large group.
Why not natural language?
o Because it is ambiguous and the machine doesn’t have the capability of interpreting it
o It is not computationally efficient (or systematic)
o It is not completely explicit
A coding language is a formal NOTATION suitable for:
(1) Describing algorithms
(2) Make explicit the meaning of primitive signs up to more complex sentence
What are the fundamental components of a coding language?
comply to syntax rules they are said to be well formed
meaning
the order of operations to be done when the instruction is executed. More in general: the ensemble of meanings
to assign to the sentences (syntactically correct) of the coding language.
Alpahbet A (lexicon) is the set of symbols (building blocks) used to build sentences
Universe A* is the whole set of sentences (finite sequence of) elements of A
A language L on an alphabet A is a subset of A* defined by specifying a formal grammar
For example: “the sky is the sun in” belongs to the universe A* because this set contains all kinds of sentences that
can be built with the symbols of Alphabet A, also non-sense sentences
“the sun is in the sky” is an example of a language L on the alphabet A because it is a subset of the universe A* whose
elements follow certain rules (like grammatical rules in this example, sogg + verb + other elements)
Formal grammar consist of:
TERMINAL symbols , building blocks. For example
declaration..
(generative), explaining how NON-TERMINAL symbols can be expanded to
I have few terminal symbols and few non-terminal symbols (the
“x” is the multiplication symbol
E stands for “expression”
T stands for “term”
F stands for “formula”
Var stands for “variable”
E à T means that if I have an “E” I can derive a “T”
I can have production rules that are only terminal only non-
terminal and also both terminal and non-terminal
An example of formal grammar (see slides to see the parsing tree)
Is “a + b” a well formed sentence of the AREX language?
Yes it is because the machine derives the final word and it happens one production rules at a time and basically creates
a parsing tree
à The machine always starts from “non-terminal” language and derives all existing and known
production rules (usually using a parsing tree) until it finds the ultimate “terminal” language
Whenever the coding program results in a language error it means that the program couldn’t
find the parsing tree for the sentence we have typed.
INHERITANCE it is the mechanism by which it is possible to derive one class from another by simply adding further
methods or specializing its internal implementation for specific cases.
POLYMORPHISM is the mechanism that allows the code to modify its behavior based on the objects that are assigned
to the current container (class) (e.g. child class and parent class container)
The functional paradigm / programming style is probably the easiest one.
⇨ The rules is to provide a function (so the name of the function) and then specify the list of elements which
includes also mathematical operators. The functional paradigm aims to unify instructions and data, and in
particular to represent instructions as specific "executable" data structures.
Considering the procedure for solving a problem analogous to the calculation of a function in the mathematical sense,
programs are constructed as functions, defined in turn by other functions
Lisp is a program that uses this functional programming language. In the Lisp language, for example, there is practically
a single construct, the list, denoted as (element1 element2 ...): each list can represent a data structure and a function
to be performed at the same time. For example, the equivalent of the imperative instruction
This language doesn’t use neither objects or functions but instead it useds “predicates”, which is an action that i order
the machine to perform on some data / parameters.
⇨ This language provides that the problem to be solved is specified by formalizing, precisely in the form of
"declarations", the characteristics of the solution rather than the procedure for obtaining it
A program written in a declarative language allows you to describe what you want to obtain from the program itself
and not how to obtain it: the conversion of the declarations from which the program is made up into instructions that
the processor can execute is in fact the task of the translator program towards the machine language, which operates
therefore also as a ''troubleshooting engine''
An example is Prolog, whose basic constructs are neither instructions nor functions, but predicates, i.e. expressions
that can be true or false.
For example, in Prolog the evaluation of the predicate plus(12,23,35) produces the value true, because 12 + 23 actually
equals 35.
This same predicate can be used to compute the value of 12+23: by executing plus(12,23,X), the variable X is assigned
the value that makes the predicate true, in a process called ''unification'' which produces the result X=35.
The unification allows to operate in a very sophisticated way: for example, by executing the construct that evaluates
plus(12,X,35) the variable X is unified with the value that makes the predicate true, therefore X=23, with the effect that
a single predicate operates to perform both additions and subtractions.
NB: Inference means to derive new knowledge from the existing one, however there is a difference between Machine
Learning/ Statistics and Coding / Logical Inference
In Coding / Logical Inference there is a deductive process of reasoning, there are some premises and from these
premises we derive results
In ML/S we have got examples from real world and we infer the rules behind those examples
There are two ways with which a machine takes the instruction provided
⇨ The interpreter takes a program instruction, decodes it, translates it into machine language instructions, and
executes those instructions, then go to the next instruction and so on, until a termination instruction is reached;
The instructions are translated every time they are executed: ex. an instruction included in a loop repeated 10 times
will be translated 10 times into the corresponding machine language instructions.
Advantages
o The hardware interpreter is generally very efficient; the software interpreter is easier to implement and for this
reason it is sometimes used to make programs portable between different hardware platforms;
o The software interpreter allows you to work directly with high-level languages, is more flexible and simplifies the
debugging and program development phases.
When there is flexibility in the interpretation, it means that any operating system is able to understand the code , so
you don’t have to re-write another specific code when switching to different operating systems
⇨ Each communication act with the machines causes an evaluation process that always returns an answer from
the machine to us
⇨ Each word of the language that we input to the machine has a type (it is an object)
⇨ Each complex sentence we use is called an expression and the evaluation of an expression causes an output
(which can be the final result or a message of error)
Python allows to assign the objects that we have declared in the previous activities to the so called “variables”
v Variables are (1) objects of a defined type (that is the type of the object they contain) and (2) their content
may vary.
This symbols are not terminal. They can vary, indeed it is possible to give
the same name to different objects. Python will perform operations based on
the latest / current value of the label.
The act of giving an object an object label/variable is called VARIABLE ASSIGNMENT and it is the only case in which
python
doesn’t return an output (because it has simply memorized the label we have provided with our instruction)
If we use object names or object labels we can avoid to address the object all the time because it is a way to
memorize my objects for further reuse in the conversation with Python.
NB: two types of divisions:
ü The strict one x / y that gives a floating number;
ü x // y it does the division but it returns only the integer part of the quotient
ü 11 % 2 it gives the rest of the division
As mentioned before, variables have VARIABLE TYPE. The type of a variable is given by the the type
of the object they contain. It is called dynamic typization of objects, it is a characteristic of flexibility
of Python with respect to other programming languages.
When we introduce variables, we don’t have to specify the type of the object we are labeling because
Python understands automatically.
When we use variable assignment, we are implicitly using Python syntax (otherwise an error would show up)
So we understand that the object name / label must always begin with an alphabetic character. It can’t begin with
numbers for examples)
For example, variables names have restrictions (try yourself to name a variable as 2num or @num or num-2 or num: 2
and see what happens….. à The assignment character cannot start with particular charters as - , +, “numbers” or others
We are using instructions (snippets in this case) such as x = 2
exercise
The application of
arithmetic operators in Python depends on the following operator precedence rules:
⇨ Expressions in parentheses are evaluated first, so parentheses can force the order of evaluation. E.g., (a / (b - c))?
⇨ Subsequently, the elevations to the power are evaluated. If an expression contains several exponents, Python
applies them from right to left.
⇨ Subsequently, multiplications, divisions and modules are evaluated. If several multiplications, divisions, and
modules appear in an expression, Python evaluates them from left to right. Multiplication, division, and moduli
have the same level of precedence.
⇨ Additions and subtractions are evaluated last. If several additions and subtractions appear in an expression, Python
evaluates them from left to right. Additions and subtractions have the same level of precedence.
the sep parameter is used with the print() function to specify a separator between multiple items that you want to print.
By default, when you use the print() function with multiple items, they are separated by a space. However, you can
customize the separator by providing a value for the sep parameter.
can be converted to a string.
this example, we specified the separator as a hyphen
("-"), so the values of x and y are printed with a
hyphen in between.
In this case, we used " | " as the separator, and it
separates the name, age, and the "years old" string
FUNCTION – INPUT (arg)
v The input() function in Python is used to take user input from the keyboard. It allows you to interact with your
Python program by providing data from the console
The snippet executes the following:
received as a
parameter , called
prompt , to tell the user what to type, then waits for the user's response
can use that string to execute the following commands à quindi python riceverà una stringa
the input using functions like int() or float(), depending on your requirements.
Ex: – int(input(..)), in this way python will transform the string into numbers of type integer!
The program prompts the user to enter their name. Whatever the user types in response is stored in the user_input
variable as a string. The program then prints a greeting using the user's input.
Example of how to convert user’s input into an integer:
we can write int(input) or also
int(Num1) e int(Num2)
NB: In Python, the str() function is used to convert an object into its string representation. It takes one argument and
returns a string that represents that object.
You can use str() to convert various data types, such as integers, floats, and booleans, into string representations.
For ex:
number = 42
number_as_string = str(number)
v A Condition is an expression of type boolean that returns value True or False
We can give python control instruction in the sense that we want to say “ if something happens do this, if something
else happens do that instead”
Pay attention because equal is given by ==
The command “=” is used for variable assignment
IF or IF…ELSE or IF…ELIF…ELSE are all admitted expressions in Python
They allow python to evaluate an expression (that is a condition) and decide whether to execute the next instruction
or not (subject to proper indentation)
ü “IF” expressions always return a TRUE or a FALSE value
How does it work?
◦ The decision symbol (diamond) contains a condition that can be True or False. The rhombus has two outgoing
stream lines
of actions) to be performed
skipped
Each Python expression (=condition) can be interpreted as True or False and is evaluated by Python as True or False
Decisions can be
based on any expression :
ü A non-zero value is True while Zero is False
ü Strings with characters are True, empty strings (".'''or ''''''') are False
zero is false. The “if” instruction follows the false
path. Twelve is true, the “if” instruction follows the
true path
Empty string is false. The “if” instruction follows the
false path. The string with character is true, the “if”
instruction follows the true path
ü Using logic operators always returns a True or False value
We use only “IF” if there is only
one condition .
We use if..elif, if…else, if…elif…else if there are more
conditions!
IF, ELIF and ELSE instructions can also be used in a compact way
An even more compact way
In Python, INDENTATION refers to the whitespace (usually spaces or tabs) at the beginning of a line that determines
the grouping and structure of code. Indentation is a fundamental aspect of Python's syntax and is used to define code
blocks, such as loops, conditional statements, and function definitions.
Here are some key points to understand about indentation in Python:
delimiters like some other programming languages (e.g., C++ or Java). The amount of indentation is crucial
for indicating which lines of code are part of the same block.
uniform indentation throughout your program. Commonly, developers use either spaces or tabs, but not both.
The Python community typically prefers using four spaces for each level of indentation.
block or control structure. For example, in a
for loop, the code within the loop has a greater level of indentation
than the for statement itself.
if True:
print("This line is indented under the 'if' statement.")
print("So is this one.")
print("This line is not indented, indicating it's outside the 'if' block.")
In the above code, the two print statements are indented under the if statement, indicating that they are part of the
conditional block. The last print statement is not indented, showing that it's outside the bloc
Another example
The last row is within the if else statement so it is executed only in
some cases.
In that case the last row is outside from the if else statement, so it will be executed whatever.
EXERCISE: Let’s try to translate the following flow into a Python program (Instructions if...elif...else)
If the student's grade is greater than or equal to 90 - Display "A"
Otherwise If the student's grade is greater than or equal to 80 - Display "B"
Otherwise If the student's grade is greater than or equal to 70 - Display "C"
Otherwise If the student's grade is greater than or equal to 60 - Display "D"
Otherwise - Display "F"
N.B. Don't forget the colon ":" and two click two times "enter" to run the code.
Only if I use the if...elif...else structure I create a statement similar to the ifelse in excel with
more conditions. If I have more conditions I need to use if:..elif...else structure. NOT
if...if...else
v In Python, the for statement is used to create loops that iterate over a sequence of elements, such as a list, tuple,
string, or any other iterable object. The for loop is designed for situations where you want to perform a set of
operations /actions for each item in the sequence.
Here's the basic syntax of a for loop:
for item in iterable:
⇨ item is a variable that takes on the value of each element in the iterable one at a time during each iteration of the
loop.
⇨ iterable is any object that can be iterated over, such as a list, tuple, string, or range.
ü The for loop continues to iterate over the elements of the iterable until it has processed all the items. When
there are no more items left to iterate over, the loop terminates
Example:
fruits = ["apple", "banana", "cherry"]
for fruit in fruits:
print(fruit)
In this example, the for loop iterates over the list fruits and prints each fruit to the console.
You can also use the range() function to generate a sequence of numbers and use a for loop to iterate over that
sequence:
for i in range(5):
print(i)
This code will print the numbers from 0 to 4, as the range(5) generates a sequence of numbers from 0 to 4.
Example a string consist of a sequence of single characters. We display the characters of the string programming
separated by two spaces
NB: The word character can also be summarized by “ c ”
With this command we are asking python to print each character
and end with a space ‘ ‘, so as a result, each character will look as
if they are separated as a space)
Why do we need to use the end= parameter?
rows — so the print function is executed for each character (in this case, eleven times)
#i want to obtain the following:
P, r, o, g, r, a, m, m, i, n, g
Code: for character in “programming”:
Print (character, ‘,’, end = ‘ ‘)
Output: P, r, o, g, r, a, m, m, i, n, g
If we write just the following command, we obtain eleven rows and our command to add
the comma between each character was not executed simply because in each row there is
just one character
if we write the following command, we are able to separate characters with commas, but actually, what the program
is doing is just printing a comma, not printing a comma to separate the characters.
length of the variable ‘prog’ (If we print(i) we obtain 11)
and end with the comma, otherwise if i is lower than 1 we print just the character
(we do this because in this way for the last character we don’t print the comma)
is fine for the last character
If we don’t use this mechanism with the length of the prog variable we obtain this so it is
a mistake because the last character g has got comma
What happens if the command is not “ i > 0” the output will be different
In correspondance of the letter “i” the variable “ i” is equal to 3
The “i” is the last character to be printed in the same row and it will be printed without
the comma.
In correspondance of the letter “n” and “g”, the variable i is equal respectively to 2 and
1, so it is lower than 3 and these two characters will be printed in different rows
if we take the previous “for” sequence and we print it again, we obtain this:
This happens because we haven’t initialized the “i” variable.
So each time we run the code the value of i changes because it is always updated and it
takes into account the previous commands. (With the first run of the “for” sequence, the
“i” is reduced from 11 to 0 because we have eleven characters, if we run the “for”
sequence again, we reduce “i” from 0 to - 11)
Solution: we have to initialize the variable “I”, which means we have to recall
always this variable
AND, OR and NOT LOGICAL TABLES
Control structures most of the time are subject to conditions that must be true or false, and in python each kind of
object can have a false or true value (for ex an empty object is false, a non-empty object is true)
AND logical à the and condition provides true only if both conditions are true
OR logical à the or condition is always trye unless both conditions are false
With the NOT logical operato, when we have true it becomes false and when we have false it becomes true
Try to implement a code / set of instruction such that, when it is run, it provides as output the “AND” logical operator
table. First print the headline of the table and then using operators create the following rows
How do we proceed?
hint: it is a combination / nest of control structures and logical conditions
The idea is that we have got a nested loop, we have got a loop inside another
First we introduce the 3 objects p q and a (p is the column “A”, q is the column
“B” and a is the column “A&B”)
Then we create the first nested “for” where we use list to indicate the possible
value that our variables can assume
so we say that p can assume the values true or false
and q can assume the values true or false
[True, False] are the iterables mentioned earlier
For the first “for” p assumes by default the value “true” —> P = T
and at the same time for the inner “for” q assumes by default the value “true” —> Q = T
The inner function is always executed before the outer function, so that it finishes the cycle
if we execute again this code, we create the second iteration
How is the inner function executed? Python remembers that at the beginning, it has given to “q” the value “True”
which is the first of the two elements of the list, so now Python gives to “q” the value “false” and in this way the list is
finished.
How is the outer function executed? it is like “blocked” so it keeps the result of the previous execution
so the inner for is executed as many times as there are elements in the list, while the outer for function is liked “blocked”
until the inner function is complete
The inner function is completed, Now we focus on the outer “for”
In the first execution p assumed “True” and now python completes the list and prints p as “False”
FOURTH EXECUTION: In this execution python prints p and q as “False”
This is the more complex formula
As you can see the only thing that changes in the code actually is the “or” in the last row
Here we try to generate the NOT table
in the case the print
function gives us
problem, we convert the
not p into a string
#this is an example of what the exam might look like
So whenever we have got a loop variable we are
expected to know what happens at each iteration of
that variable
Development of an algorithm with
Once you know the requirements of the problem, you can start creating an algorithm that solves it. Then you implement
the solution in a program.
The algorithm to solve this problem must:
ü keep a total of grades
ü calculate the average, i.e. the total number of votes divided by the number of votes;
ü view the result.
For this example we put 10 votes into a list
We use blank lines and comments to break the script into three stages of execution: initialization; processing, and final:
these variables. à We have to wild the memory of the program, in other word we have to define the variables
needed and of course we need to have our goal clear in mind
analysed.
and displays the class average. Many scripts can be decomposed (or broken) into these three phases.