Docsity

Appunti It coding and application, Appunti di Programmazione e Tecnologie Web

Toggle sidebar
bg1
IT CODING AND APPLICATIONS
Lesson 1 – 21/09/22
Computer memory
We know that there are many memory cell: each cell is called is called bit (which means binary digit) and it can contain either 0
or 1. These cells are grouped into sorted sets called bytes.
byte is composed by 8 bit.
Computer memory is an indexed collection of bytes.
Every memory location (byte) contains 8 bits, each memory location is associated with a progressive address.
The number of memory locations N is called memory capacity.
Computer memory is composed by a very large number of byte, we use prefix to describe memory capacity.
There are different types of memory: the main memory (RAM, Random Access Memory) which is volatile (the content is lost
after power off), extremely fast, moderate capacity (tens of Gigabytes) and the external memory such as hard disks, usb keys
and SSD which is prescience (content is preserved when powered down), very slow and large capability (several Terabytes).
Information
Computing is basically retrieving the content of memory cells, changing the bit values according with given logical rules and
storing back the processed bit into (other) memory cells.
Bits can represent different kind of information, such as number, text, image and audio and multimedia content.
For example, it is possible to represent numbers:
For example, it is possible to represent text:
Text can be seen as a sequence of alphabetic characters representing single letters [a-z, A-Z], numerical digits [0-9] and
punctuation symbols. Using one byte we can store 256 different patterns of bit (ranging from 00000000 up to 11111111). We
can associate different patterns of bits to alphabetic characters.
pf3
pf4
pf5
pf8
pf9
pfa
pfd
pfe
pff
pf12
pf13
pf14
pf15
pf16
pf17
pf18
pf19
pf1a
pf1b
pf1c
pf1d
pf1e

Anteprima parziale del testo

Scarica Appunti It coding and application e più Appunti in PDF di Programmazione e Tecnologie Web solo su Docsity!

IT CODING AND APPLICATIONS

Lesson 1 – 21/09/ Computer memory We know that there are many memory cell: each cell is called is called bit (which means binary digit) and it can contain either 0 or 1. These cells are grouped into sorted sets called bytes. byte is composed by 8 bit. Computer memory is an indexed collection of bytes. Every memory location (byte) contains 8 bits, each memory location is associated with a progressive address. The number of memory locations N is called memory capacity. Computer memory is composed by a very large number of byte, we use prefix to describe memory capacity. There are different types of memory: the main memory (RAM, Random Access Memory) which is volatile (the content is lost after power off), extremely fast, moderate capacity (tens of Gigabytes) and the external memory such as hard disks, usb keys and SSD which is prescience (content is preserved when powered down), very slow and large capability (several Terabytes). Information Computing is basically retrieving the content of memory cells, changing the bit values according with given logical rules and storing back the processed bit into (other) memory cells. Bits can represent different kind of information, such as number, text, image and audio and multimedia content. For example, it is possible to represent numbers: For example, it is possible to represent text: Text can be seen as a sequence of alphabetic characters representing single letters [a-z, A-Z], numerical digits [0-9] and punctuation symbols. Using one byte we can store 256 different patterns of bit (ranging from 00000000 up to 11111111). We can associate different patterns of bits to alphabetic characters.

Unicode Some languages (Arab or Chinese) are not based on an alphabetic set. Unicode is an information technology standard for the consistent encoding, representation and handling of text expressed in most of the world’s writing systems. It uses two or more bytes to encode each writing symbol. Image representation It is the most popular representation for images is based on a raster (or bitmap) format. Image is described by a matrix (𝑛 × 𝑚) of pixels where: n and m represent the vertical and horizontal resolutions and the (𝑛 × 𝑚) the overall image resolution. For example, a 48MP image is an image composed of 48 millions of pixels. We need to describe the color of each pixel. For black and white images, we can associate one bit to each pixel, for gray scale images we can use a gray palette and for each pixel we need to describe its amount of darkness. Humans can distinguish among about 10,000 gray levels. We need two bytes for each pixel to describe its gray level. All colors can be obtaining as a mixture of primary colors; in computer science the most popular representation is based on adding Red, Green and Blue (RGB). Using one byte for each of the three primary colors we can describe 224 ≈ 16 millions of colors. Audio What is a sound? It is a vibration (i.e., sound pressure) that propagates as an acoustic wave. In any given point we can measure this vibration as a function of time 𝑓(𝑡). To describe any sound, we need to describe the temporal behavior of 𝑓(𝑡). The number of sampling rate and the number of bits used to encode each sample determine the quality of audio digitalization. Spectrum theories based on frequency analysis state that humans cannot hear more than about 40,000 samples per seconds encoded with 16 bits. Audio best bit rate: 40 , 000 × 16 = 640 𝐾𝑏𝑖𝑡 𝑠 =^80 𝐾𝑏𝑦/𝑠. Top quality audio is encoded at 160Kbyte/s. Compression To reduce the amount of memory cells required to store any piece of information (and to achieve better steaming quality of service) the contents are usually compressed. Compression is based on rule that reduce the number of bytes require to store a given content. There are two large families of compression techniques:

  • Lossless compression (e.g., zip, rar). This kind of compression works bad with multimedia content and audio.
  • Lossy compression (e.g., jpeg, mp3). Reduce in a very significant way the number of bytes needed. tradeoff between compression and quality of content. For example, the more we compress the image the lower the quality of the image will be. Type of information Since all types of contents (number, text, image, audio and video) are described as a sequency of bytes to interpret any content we need to know the type of information they refer to (data type). This information which the sequence of bytes is referred to is called the data type. As a result, if we sum data and data type, we will have information content. Data type allows us to perform given operations, such as sum and sorting. The data type is mandatory because allows us to make some operations. It is the information of which kind of information is stored in a given area. Computing architecture Very high-level description of how a computer works without dealing with internal technicalities Von Neuman architecture: CPU: central processing unit, contains the electronic circuit that allows to execute the computing. Main Memory, and input / output devices. This is the architecture of the general part of the computer.

Basic tools for Computational Thinking Abstraction is the ability to filter out information that is not strictly necessary to solve a certain type of problem and generalize the information that is necessary. It is the art of taking the details out of a problem so that you can make a solution work for many different things. In the previous example, it does not matter that we want to sort a set of numbers, what is important is that we are able to compare a pair of items and decide which one is greater. For example, 10 > 1, “zeta” > “alpha”. A generalization is the formulation of general concepts from specific instances by abstracting common properties. When we are facing a problem, in most of the cases the problem is just one of the many we need to solve. Instead of sorting this set of numbers {1, 3, 2} we want to devise a method for sorting an arbitrary set of numbers Even better, we want to sort a set of comparable items. For example:

  • A daily planner uses abstraction to represent a week in terms of days and hours, helping us to organize our time.
  • A world map is an abstraction of the earth in terms of longitude and latitude, helping us describe the location and geography of a place.
  • In mathematics, we write generalized formulas in terms of variables instead of numbers so that we can use them to solve problems involving different values. Coding Coding or computer programming is the process of designing and building a computer program (i.e., a sequence of simple steps that can be executed by the computer) to perform a specific task. At the root of programming there is the concept of algorithm an abstract way for describing the process used to solve a problem Lesson 2 – 23 /09/ A program is a way to communicate instructions to a machine in order to execute a desired task: you should thank a code developer for the fact that you can use Whatsapp to chat with your friends or Google to search things on the web. Unfortunately, computers do not understand English or other natural languages spoken by humans. They only understand a particular language known as machine language, made up binary digits. Lesson 3 – 28/09/ Algorithms An algorithm is like a cooking recipe: it must be followed exactly; it must be unambiguous, and it must have an end. An algorithm is an ordered set of unambiguous , executable steps that defines a terminating process. Is an ordered set because you must define the precedence among steps, is unambiguous because it must have a unique well defend interpretation, is executable because it doesn’t require any creative skills and it defines a terminating process because it can’t run forever. It is important to emphasize the distinction between an algorithm and its representation—a distinction that is analogous to that between a story and a book. A story is abstract, or conceptual, in nature; a book is a physical representation of a story. If a book is translated into another language or republished in a different format, it is merely the representation of the story that changes—the story itself remains the same. There are various techniques to represent algorithms:
  • Schematic/graphical (for humans). It is not dependent on any programming language, so it is easy to understand for anyone even without programming knowledge, and we mean pseudocode and flow chart.
  • Coding which is the representation of an algorithm in a specific computer programming language. Algorithms primitives It means building blocks for algorithm representations. Primitives represent very common sematic structures like execution, conditional and iterative statements. A collection of primitives along with a collection of rules stating how the primitives can be combined to represent more complex ideas constitutes a programming language. Each primitive has its own syntax and semantics: syntax refers to the symbolic representation while semantics refers to the meaning of the primitive. Data representation A very common primitive is aimed at handling with data, which is any information requested by the algorithm. The standard way to represent data is to assign symbolic name to be used as a placeholder to refer to data. name <- data. We can refer to data by using the name placeholder. Execution or assignment primitive The container (usually named as variable) stores some information, while the information/data is inside.

Name <- data, Year <- 2022. Semantic : allocate a memory area (referred as “year”) suited for storing the integer value 2022. Syntax : variable name, any sequence of character (must begin with alphabetical letter). Ex: b <- a + 1 Get the content of variable a, sum one and store the result on a variable named a. All variables used in the expression have to be previously defined. C <- 10 E <- c + d In this case variable d is undefined. Very often “=” is used as “<- “, a=10 instead of a<-10. Variable names must start with an alphabetic letter: Error: 1year=10. It must be year=10. Variable names can’t contain spaces: Error: my name = “Daniele”. Variable name is sensitive. myName and myname are two distinct variables. Best practice rule: use self-descriptive name. Es: year=2022 is correct, while x=2022 is incorrect because it’s not easy to understand the role of variable x. name = expression can be any computable expression evaluated according to arithmetic precedence rules. a + b * c - > must add the value of a to the product bc*. The nature of the information stored on a variable, usually named as data type , determines which operations can be executed and how to compute their results. Es: 5/2 =? Integer data type: 2 Floating point data type: 2. Basic data types are numeric , string , Boolean. Numeric data type Numeric data types are used to store numbers (both integers and real values). Ex: A = 5, B =2.

Boolean expression Boolean expression is a combination of Boolean operations/operators (x >= 10) and (x <= 20). The evaluation of Boolean expression is terminated as soon as we are sure about the results. E.g., assuming x=5 will prevent the evaluation of the second operand (Why?) Boolean expression can be very complex! Every computer program can be described as a Boolean expression… Collection is a grouping of some data items (possibly zero) that have some shared significance to the problem being solved and need to be operated upon together in some controlled fashion. Es: a list (or set) of numbers to be processed. X = [1, 2, 3], X refers to the whole set, X[index] refers to individual item of the set. Index ranges between 0 up to (numberOfItems - 1 ). Algorithm description Pseudocode is a plain language description of the steps of an algorithm. Pseudocode often uses structural conventions (semantic building blocks) of a normal programming language but is intended for human reading rather than machine reading. It’s more flexible than coding and programming languages. It typically omits details that are essential for machine understanding of the algorithm (programming language specific directives). A flow chart is a type of diagram that represents a workflow or process. A flowchart can also be defined as a diagrammatic representation of an algorithm, a step-by-step approach to solving a task. An execution statement is a simply indivisible execution step. We do all the action related to the single execution statement. Examples:

  • year=
  • a = b+c
  • 𝑎 = cos( 2 ∗ 𝜋 ∗ 𝑥)
  • print(“Hello World!”) A control flow is the order in which individual statements (i.e., primitives) are executed. A sequence of statements is named block: statement 1 statement 2 … statement n Conditional primitives alter the control flow depending on whether certain conditions are True or False if condition : if a > 0: statement: numberRange = “a is positive” Indentation identifies the statement to be conditionally executed. We always can substitute a single statement with a statement block. We can conditionally execute a block of statements.

One is a conditional statement and another one is an executional statement. If the condition is false, we skip the executional statements. Statement K is executed anyway, independently from the result of the evaluation. Two alternative conditional statements: If the condition is false, we execute the statement 3. At the end we are going to execute statement 4 anyway. So, we reach the same result independently by the evaluation of the previous statements. The idea is making it easier to understand by humans. Iteration primitive Repeating the execution until a condition is true. Another common semantic structure is the repeated execution of a statement or sequence of statements as long as some condition remains true. Repeating the evaluation is very easy for computers because they are very fast. while (special keyword to identify the start of an iteration) condition: statement 1 statement 2 statement 3 if the condition Is still true, we keep this process until we find a condition false. Then we exit and we go to statement three. on the iteration primitive statement, after executing the statement I go back to evaluate the condition. We do that as many times as the condition remains true. We pass to the next statement 3 only whent the condition becomes false.

Scope refers to the visibility of variables. In other words, which parts of your algorithm/program can see or use it. Scope of variables:

  • Spatial (parts of code)
  • Temporal (time window of the execution time) Global variables (defined outside functions). Most common activities are already coded and available as functions. Function stored in library (packages) are available (imported) for our programs! Lesson 4 – 05/10/ From Algorithms to Programs Algorithms describe the solution process Programs are the implementation of algorithms on a given programming language Algorithms are designed for human comprehension whereas programs have to be “understood” by a computer! Programing languages are designed to be easily understood by computers and hence have strict syntax and grammar rules! For example, the Tab key (usually placed on the left side of your keyboard) has a different role than a few spaces (la large key at the bottom of your keyboard).
  • Computers only understand a very basic language named machine language (vary accordingly with the CPU model, e.g., Intel, AMD, ARM, Apple Silicon)
  • Machine languages are composed of very basic primitives:
  • Getting some data stored in some main memory location (RAM)
  • Performs some basic arithmetic/Boolean operations Store the result in the main memory (RAM) !!! How computer execute programs Although machine language programs are very efficient this type of coding is reserved to very specific tasks (very far from IT Coding and Applications goals). Most of modern programming language use high level primitives that ease programmer duties (these primitives are very close to ones used by algorithm pseudocode).

A program coded with a high-level programming language is named source code. This source code is from a computer point of view a file of text. We need a special program that translated source code in order to execute it on the computer. Some special programs take care of translating source code to a set of machine executable instructions. There are two ways in which the computer can execute the code: Compiled languages , a special program ( complier ) translates the source code into a specific machine language. The output of the compiler is an executable program that can be executed. Interpreted languages , a special program ( interpreter ) reads and processes one by one each source code instruction. For each instruction, the interpreter executes all the actions associated with that instruction before moving on the following instruction. Programming paradigms In science and philosophy, a paradigm is a distinct set of concepts or thought patterns, including theories, research methods, postulates, and standards for what constitutes legitimate contributions to a field.

  • Procedural paradigm: Concept of procedure, set of computational steps to be carried out (see the Program Unit concept).
  • Object Oriented paradigm: Objects that expose behaviors (methods) and data (attributes), Identification of main entities, Program execution as a simulation of the represented “world”. You focus on the noun of the concept. Programming languages There are hundreds of programming languages targeting specific frameworks (scientific/engendering, data processing, web applications, micro services, ...). For example, Python is an interpreted, high-level and general-purpose programming language allowing rapid prototyping. Python's design philosophy emphasizes code readability with its notable use of significant whitespace. Its language constructs and object-oriented approach aim to help programmers write clear, logical code for small and large-scale projects. Python is an interpreted language. Reserved keywords (special meaning) and cannot be used as ordinary identifiers. The basic data types are integer numbers.
  • Floating Point Numbers: largest value is about 1. 79 × 10308 smallest value is about 5 × 10 −^324
  • String (sequence of characters) name = ‘Daniele Tessera’
  • Boolean Operators A very common operation is to alter the value of a variable. There is the concept of updating a value.
  • variable = variable + x
  • variable += x this indication means “add what is on the right of the symbol to the variable on the left”. For example, if x = 10, then: Logical operation a == b: compare the content of two values and check if the content of these values is equal. a!=b: check if the content of the values is different. Test if two variables refer to the same data a is b a is not b a= b=10. a==b  True a is b  False

Sometimes we need to pick up only a few elements inside a given range letters [startPos:lastElement:distanceBetweenElements] srartPos: the position of the first selected element. lastElement: last element to be considered. The slice operator selects a subset of elements, that is, of element positions How these positions are computed? nextPosition = currentPosition + distanceBetweenElements Example: letters = [ ’a’, ‘b’, ‘c’, ‘d’ ,’e’, ‘f’, ‘g’] letters[1:6:2] Methods Methods are functions applied to given data structures (ref: O.O. paradigm) Syntax: name. methodName ( ) The presence of optional parameters changes the actions executed by the method itself (this behavior is named polymorphism) l=[‘a’, ’b’, ‘c’, ’d’]

The conditional statement The if word tells the interpreter that there is a condition with a Boolean result. if condition: statement 1 ….. statement n statement n+ Sequential search PROBLEM: we want to check if a given element is present on a given list mylist = [ 3, 1, 2]

  • Is the element 2 present in mylist?
  • Is the element 4 present in mylist?

Computational thinking requires to identify a procedure to solve the problem Let try to “fool” our intuition mylist=[1, 7, 10, 4, 5, 78, 41, 0, 12, 17, 32, 28, 19, 7, 15, 24, 45, 3, 55, 2, 20] Is 2 present in the list? There is an index that refers to a certain number inside the list and checks if the number is present or not in the list. We need to have a placeholder to analyze each element of the list. Then we consider the current element and we compare it with the target value- if it is equal, we can provide the answer. Otherwise, we move to the following element. When. We reach the end of the list we can provide the answer. mylist = [ 3, 1, 2] x= n=len(mylist) i= found=False while not found and (i < n): if mylist[i]==x: found=True else: i += 1 if found:

Lesson 4 – 07/10/ Data type

  • int: integer. print(type(a))
  • float 2.5.
  • bool : Boolean, which is true or false (true=1, false=0). Ex: bool(1) - > true ; bool(0) - > false. Every integer that is not 0 gives as a result True. While bool([]) - > false. The type(True) is bool. print(type(0)) = <<class ‘bool’>> print(type(0)) = <class ‘bool’>> ex: 10 – True - > 9 bool(-1) - > true
  • print(type('hey,how are you?')) - > <class ‘str’> Strings are immutable, once you define them, you can’t change a character alone, because they are all connected one to each other. Function build inside the concept of string. string.upper() - > ‘HOW ARE YOU?’ list : there are more information stored in that object. When you name a valuable, it must be named properly, you must choose a proper name. it is not possible to put a space because a space is not correct in Python. Valuables must be named in names that explain what the value is. You can’t find a minus 1 element of a Boolean.

If we want to substitute an element in a list, it is possible because lists are not only data types but also data structures so it is possible for us to change an element inside a list. The append method is a method written like this my_list.append means adding a new element to the list. The insert method allows to have a new character inside the list, not at the end of the list like the append method. In the append we didn’t put the square one in front of 4, because it is an integer. The pop method is useful for deleting an element from the list. There are 4 types of data types that we need to know: dicit, tuples, sets.

an error has been made in this case and is an arbitrary error, which is the 0. This algorithm works only with positive numbers and not with negative numbers. The 0 as maxValue is an arbitrary choice that has some implications. The initial value must be one of the list values. The output is 0! If we are using an empty list we should use none. Another example: mylist = [ - 1, - 4, - 2, - 7, - 12, - 4 ] maxValue = mylist[0] for i in range(1, len(mylist)): if mylist[i] > maxValue: maxValue = mylist[i] print('The largest value is:',maxValue) here we are not considering the element with index 0. The right one to use should be this one: mylist = [ - 1, - 4, - 2, - 7, - 12, - 4 ] maxValue = mylist[0] for x in mylist: if x > maxValue: maxValue = x print('The largest value is:',maxValue) Program unit (Python function) A function is a block of organized, reusable code that is used to perform a single, related action. It allows us to define new reusable abstract tool.

  • We can use function by simply indicate the name of the function to be called  len()
  • You can pass data , known as parameters, into a function  len(mylist)
  • A function can return data as a result  n = len(mylist) We must define the code out function is composed of. A function is a block of code which only runs when it is called. def functionName ( parameters ): statement 1 statement 2 … statement N return (value) Statements placed here are not part of the function. For example: def printHello (): print(‘Hello World!’) print Hello() defining the function and executing the function in order to make it clear to the interpreter that we want to call the function we must use the round parenthesis after the name even if we are not providing any parameter in it.

This variable can be referred only inside the function mean. Because they are created only during the execution. After you exitv from the function with the return statement, terminate the execution of the function and provide this value as result. After we terminate the execution, all boxes are destroyed. Scope is the portion of code in which we can refer to a variable. The scope of the variable sum is just after its definition at the end of the function. Formal paramete r is the placeholder used in the definition of the function: this parameter doesn’t even exist when we define the function. It is def mean(mylist) When I am calling the function, we have the real information that is called actual parameter. During the execution there is the binding between formal parameter and actual parameter. It is print( mean(mydata) ) Functions can have kore than one parameter. For example, function that sums three values: def sum(a, b, c): return(a+b+c) print(sum(1, 2, 3)) form - > actual parameters from left to right. a=1, b=2, c=3. This is called positional assignment. Function parameters can have default values, that is, a value to be assigned if the corresponding actual parameter is missing def sum(a, b, c=0): return(a+b+c) print(sum(1, 2, 3)) print(sun(10,20)) Since actual value of formal parameter c is unspecified it will be set to its default value (in this case it is equal to zero). Packages Once our functions are coded, we want to put our functions in collections called packages. Functions are usually collected in a library, named package. Packages can be imported in your Python environment to add abstract tools (i.e., already coded functions). For example, mathematical functions (e.g., trigonometric ones) are coded in a package name math) Before using any function provided by a package we must add (i.e., import) the package to our programming environment The Ptyhon statement to add package is: import packageName packagename.function(…) Packages can also define constants (i.e., special variables with immutable values) packagename.constantName Import import math print(math.pi) print(math.sin(math.pi/2)) import random print(random.randint(1,6)) print(random.randint(1,6)) print(random.randint(1,6))