Docsity
Docsity

Prepara i tuoi esami
Prepara i tuoi esami

Studia grazie alle numerose risorse presenti su Docsity


Ottieni i punti per scaricare
Ottieni i punti per scaricare

Guadagna punti aiutando altri studenti oppure acquistali con un piano Premium


Guide e consigli
Guide e consigli


Introduction to Programming with Python: Fundamentals and Concepts, Appunti di Elementi di Informatica

An introduction to programming with Python.

Tipologia: Appunti

2019/2020

Caricato il 05/03/2020

giulia-rizzuto-2
giulia-rizzuto-2 🇮🇹

2 documenti

1 / 15

Toggle sidebar

Questa pagina non è visibile nell’anteprima

Non perderti parti importanti!

bg1
Python - introduction
Von Neumann architecture
Computer is made out of 3 basic components, linked together by communication channels called
BUS:
CPU: is the processor that performs the basic simple operations in the program. Speaks
machine language (0/1)
Memory: to store data and instructions. ROM, RAM, mass storage (hard disk, flash
memory...)
Input and ouput devices: keyboard, monitor…
Machine language
Programs need to be executed by the CPU, so they need to be translated to machine language.
Each digit of the language (0 or 1) is 1 bit.
8 bits = 1 byte = 1 single datum
Modern computers have big memories (gigabytes, billion, or terabytes, trillions of bytes)
Each type of data is stored in a different way:
oNumbers easily converted to binary. 0 to 255 can be stored in just one byte, after you
need more.
oCharacters:
ASCII standard (American standard code for information exchange) is made
of 128 numbers associated with as many characters (English alphabet,
punctuation…)
Unicode coding system contains more characters also from other
languages. It is compatible with ASCII so it is becoming the standard.
pf3
pf4
pf5
pf8
pf9
pfa
pfd
pfe
pff

Anteprima parziale del testo

Scarica Introduction to Programming with Python: Fundamentals and Concepts e più Appunti in PDF di Elementi di Informatica solo su Docsity!

Python - introduction

Von Neumann architecture Computer is made out of 3 basic components, linked together by communication channels called BUS :  CPU: is the processor that performs the basic simple operations in the program. Speaks machine language (0/1)  Memory: to store data and instructions. ROM, RAM, mass storage (hard disk, flash memory...)  Input and ouput devices: keyboard, monitor… Machine language Programs need to be executed by the CPU, so they need to be translated to machine language. Each digit of the language (0 or 1) is 1 bit. 8 bits = 1 byte = 1 single datum Modern computers have big memories (gigabytes, billion, or terabytes, trillions of bytes) Each type of data is stored in a different way: o Numbers  easily converted to binary. 0 to 255 can be stored in just one byte, after you need more. o Characters:  ASCII standard (American standard code for information exchange) is made of 128 numbers associated with as many characters (English alphabet, punctuation…)  Unicode coding system contains more characters also from other languages. It is compatible with ASCII so it is becoming the standard.

Program A program is the set of statements through which the computer executes an elaboration (task). These instructions are made of lines of codes (LOCs), in different coding languages. A programming language is an interface for giving a computer the instructions needed to solve problems. Top-down approach: from general picture, I split to specific actions  algorithms. Programs are usually stored in mass memory (hard disk, flash ROM, or memory cards for mobiles). When the program is run, it is copied to the RAM (central memory) and then executed by the CPU. But to arrive to the CPU, the source code (specific coding language) needs to be translated to machine language (0/1) process of translation: 2 ways:

  1. COMPILATION The software is compiled through a specific command and produces an executable file (.exe). From this moment, it is not necessary anymore to translate the program => faster. It is though more difficult to change or correct the code (we need to come back to the code, correct it and recompile it). Faster to execute, but difficult to change the code
  2. INTERPRETATION The software is translated and executed instruction by instruction from a software that acts as an interpreter. Slower to execute but easier to analyze and correct. Python is an interpreted language. Different steps to develop a complete program: Analyse  Design  Implementation  Test  (eventual debugging  design…)  execution Assembly and other languages In 1940s, at the beginning of programing, coding was made on punched cards, with 0 and 1. In this time, the Assembly language was created to simplify the programming process. It started to be used in the 50s when computers became capable of storing programs, instead of being just a system of switches and cable. Assembly first produced some mnemonic words that could do some actions instead of the 0 and 1 ( mul for multiplication). The Assembler then translated the code to machine language. It is a low-level language, difficult to use and similar to the machine language. High-level languages, such as Python and Java, developed later. They are mainly divided into declarative and procedural languages: Declarative languages describe reality and declare the required objective, without implementing a resolution paradigm.

Programming with Python

Python has many keywords which cannot be used for other purpose than the one they have (def, and, or, if, else, try, except, return). Then there are operators, that performs actions (+, -, /, * …). Numbers use the dot as a decimal separator: 6.0 or 654.5. Python is rigid with indentation, but not with spaces between operators, keywords ecc. It is also case-sensitive.

String of text

Escape codes \

Special command consisting of a character preceded by a backslash \ and placed inside a string. \n  wrap text (va a capo) \t  tabulation \  backslash (otherwise it would consider it something else) \’  quote (otherwise it would consider it something else) \”  double quotes (otherwise it would consider it something else)

Managing spaces and shifts

All in the same line in the code, but in different lines in the output: \n All in the same line in the output, but in different lines in the code: \ (shift) Different lines in both the codes and the output: Different prints for each line or enclose the string in triple quotes “”” bla bla bla””” or ‘’’bla bla bla’’’ If I want to do a different print but without going on a new line in the output: Print(“bla bla bla”, end = “ “ ) If I want to add a tab \t

Managing comments

Comments are short notes that explain the code. They can be entered in two ways:

  1. in front of a line of text (also continuing in the line of code)

  2. With triple quotes or apostrophe, and like this they can span multiple lines (called documentation string or docstring )

Operations with numbers

Operators can never be implicit. You can wrap the code of operations in the same way we wrapped text. ( \ ) Important: normal division (/) always returns a floating number  4/2=2. The maximum number of decimal digits shown here is 16.

Format

format ( number, ‘.2f’) The function has two arguments, the number to be formatted and the format specifier  .2 means that we round the number to the second decimal  f specifies the format, in this case floating-point number Other type of format specifier: .2%  percentage with two decimals %  percentage ,.3  thousand separators, 3 decimal digits ,d  thousand separator in an integer Functions There are built-in functions and other that come from libraries you need to import. But we can also create custom functions. When we type the name of the function and open brackets, the Call Tip appears, suggesting the syntax of the function. Non-mandatory arguments are written as Argument = desired_parameter Built-in functions. print(“string”, “string”, sep=’ ‘, end= ‘\n’)

There are then other functions, that are part of Python standard libraries, that need to be imported into the current session before being used. Then there are third parties libraries that need to be installed and imported. This is to make the memory clearer. Typing “dir ( library_name )” in the shell, we can have a list of all the functions contained in the shell. ( “dir ( builtins )” for the list of built in functions). After you import a library, you can use all the functions present in the library writing: library_name.function_name(…) statistics.mean (tuples or lists) math.sqrt (number) math.sin (number) math.cos (n) math.tan (n) random.random() Generates a random floating-point number between 0 and 1 random.randint ( a, b ) Generates a random integer number between a and b Custom functions They are blocks of code to which a name is assigned and that are executed when that name is called. Each function can be created to perform a specific task, also so that the program becomes clearer and easier to write, read and correct, as it becomes modular. Modular program = program in which each task, or the most recurrent ones, is performed by a specific function. Defining a function def function_name (parameters): instruction instruction instruction … First line is the header, then the instructions are the body of the function. Name of the function must:  have as first character a letter, or an underscore, and as other characters numbers, letters or underscores  not contain spaces  not be a Python keyword  Remember: Python is case sensitive! Arguments :  Are parameters, placeholders  datas passed to a function are called arguments  If some parameters (mandatory) have been specified in the definition, the function call must specify the same number of arguments  Mandatory parameters need to be specified first, followed by the optional ones  Optional parameters must indicate the default value that parameter must assume if not specified otherwise.  Are not required: if one writes “ ()”, then the function will need no input

 Position is important when calling. If we want to skip a parameter or define the parameters in a different order, we can simply write parameter_name= value ( keyword argument )  We can either write parameters by position, by name, or by both but writing the argument by position first and then the keyword arguments (otherwise Error) def function_name ( mand1, mand2, optional1 = 3, optional2 = 1 ) To use the function, we need to call it. When Python needs to manage a function within a program, it keeps all the functions with their instruction blocks in memory, so that it can use them when executing the code.

Productive functions

It is a function that performs a specific task and then returns a value to the instruction that called it. It always end with the ‘return’ statement def function_name (parameters): instructions return expression If we call the function by writing Var = function () And the function contains a return statement, the expression after the return will now be stored in the variable var. Without the return statement, the result of every function is lost. Example: def calculate1 (num1, num2, num3 ): print (num1 * num2 / num3) >>> y = calculate1 (4, 5, 2)

>>> print (y) None Instead, def calculate2 (num1, num2, num3 ): result = num1 * num2 / num3) return result >>> x = calculate2 (4, 5, 2) >>> x

>>> x + 2

In the first case, the variable y is empty and this way we can’t reuse the result of the function. This is called a void function (a function without the return statement, and that do not pass anything to the calling instructions). In the second case we a productive function. If you use loops and conditional statement inside of function, the return must be put at the end of each of them (or of the ones where we want to return something), or outside them (to be valid for all of them).

There are also other types like tuples, lists, dictionaries. The type function allows identifying the data type of a variable. When there are operations with numbers:  Int operation int = int  Float operation float = float  Float operation int = float (mixed data type expression) Decision-making structures 2 tyoes of control structures: Up until now we have seen sequential structures that are executed in order one by one. But sometimes structure need to allow decision: choose between set of actions A or B. This requires another type of control structure, the decision-making structure. If the given condition of the square box is true, the alternative path is taken, otherwise the structure is excluded. These are implemented through conditional statements. if condition: statement 1 statement 2 … The first line (header) is the if clause , while a block of code (the body) follows, holding the statement that are to be executed if the condition is true. If it is false, the block is skipped and the program runs on. At least one statement is required in the block of code. Simple decision  without else Alternative  if else Chained  if elif else / if elif

All the conditions of the statement are Boolean expressions (i.e. comparison that can return True or False). True and False with initial upper case!! Comparison operators act only on variables and values of the same data type. If they are different data types, Python raises an Error. More complex condition can be written thanks to the logical operators, that allow to express cumulative or alternative multiple conditions. The most common logical operators: and, or, not. The not swap the original value of the Boolean expression, turning it negative. If we want to have a condition that turns true if some value is present in a range/list, we can write: If variable in range (a,b) or if variable in [a, …., n] For double-alternative decision-making structure, which implies two different branches (execution paths), we use if and then the else. If the if clause is False, the execution of the program continues in the else block statement. We can nest several if and else statement ( nested conditions ), or we can, to avoid indentation, use the elif: if condition 1: statements elif condition 2: statements … elif condition n: statements else: statements The pass statement We use it when we want to temporarily write an empty if structure, without any statement inside (avoiding an error). For instance, if we want to test the branches of a program or if we want to go along with the next statement. When ‘pass’ is executed, nothing happens, but we pass to the rest of the code. Loops: iterative structures Loops are used to execute several times the same operation. There are loops controlled by a condition (while), actions are repeated just when the condition returns true, and loops with a counter (for), in which the line of code is repeated a given number of times. The while loop while condition:

Sequences are of different kinds, but mainly mutable , their content can be changed, or immutable , their content cannot be changed after it has been created.  Mutable : lists  Immutable : tuples, strings

Indexing

Indexing is a way to access single elements of sequence, as each element within a sequence is identified by an integer, its index. Indexing starts from 0, or if we look from right to left, from - (proceding -1) To access an item within a sequence we must write: Sequence [ index ] If the sequence is mutable, we can use the same syntax to modify the elements: Sequence [ index ] = new_element

Slicing

Selecting multiple element of a sequence at the same time using the indexes. Sequence [start:end:step] You select from the element with index ‘start’ to the element before the element of index ‘end’. If the step is negative, also the other two must be negative, or positive but with the end and start indexes switched. We can replace multiple elements at a time through the slicing.

Strings

A string is a sequence of characters (alphanumeric or symbols). Operation with strings:

  •  concatenation (only with same type of data) *  repetition In  returns True if the string is found in another string, False otherwise. Not in  (contrary) Is  Returns True is two string are identical Is not  (contrary) Function and methods

Functions: len (), max(), min()  the highest/lowest letter, from an alphabetic point of view. Methods are functions that belong to a certain object. Thus, the name of the objects must always be specified: Object.method_name (arguments) Take into account that strings are immutable, so most of the methods return a copy of the string. There are also: .capitalize  copies the string with the first letter in upper case and the other lower case. .strip(car=” “)  returns a copy without spaces (or without some other character you choose) .replace (old, new)  returns a copy with all the substrings old replaced by the new. iterable.split(“separator”) myseparator.join (iterable)

List

A list is a collection of different data ( elements ). Elements are enclosed in square brackets [], separated by a comma. Elements can have different data types. The list function transforms objects, such as strings or iterable objects, into lists. Operations with strings :

  •  concatenation *  creates copies of a list and merges them into a new list In /not in  returns True if element is found in the list, otherwise False. Methods and functions Functions: len(), list(), max(), min(), sorted(), sum() Max and min here: if elements are strings, they return the one beginning with the minimum (or max) alphabetical character. We can’t when a list contains alphanumerical caracters at the same time (TypeError: “>” not supported between ‘str’ and ‘int’). Sorted function returns a new list with values sorted in ascending order. Sum function can only be used when the list is made up of just numbers.