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


SUMMARY: Computer Science - Python, Dispense di Informatica gestionale

L'architettura di Von Neumann, la programmazione, gli algoritmi, il linguaggio di programmazione, Python e le sue caratteristiche, le strutture di controllo, le variabili, i dizionari, le proprietà delle sequenze e dei dizionari, gli oggetti, le istanze e le classi, il metodo costruttore __init__.

Tipologia: Dispense

2020/2021

In vendita dal 22/06/2022

rebeccacordioli
rebeccacordioli 🇮🇹

5

(1)

28 documenti

1 / 8

Toggle sidebar

Questa pagina non è visibile nell’anteprima

Non perderti parti importanti!

bg1
VON NEUMANN ARCHITECTURE
The CPU understands the machine language, which consists of 0 and 1.
PROGRAMMING
It is basically teaching a machine how to perform a certain task or solve a certain problem.
ALGORITHMS
An algorithm is a process that allows the user to solve a problem through a finite number of simple steps.
MACHINE LANGUAGE
In the Fifties, programs were all written with 0 and 1.
Instructions were long sequences of bits (binary digits) and corresponded to very simple actions.
Writing a very simple program required large amounts of time and extremely specialized technicians.
Going through decades, programming languages have evolved towards natural language and got far from 0 and 1 alone. But even the most
sophisticated language has to be translated into machine language (0/1) to be understood by the machine.
PROGRAMMING LANGUAGE
A programming language is an interface for giving a computer the instructions needed to solve a problem.
Many different programming languages exist: they have different syntax, but basically do the same things and share most of the logic and
rules.
Programming languages enables the communication between man and machine, like natural languages do between individuals.
SOFTWARE PROGRAM
It is a sequence of statements through which a computer executes an elaboration.
Python
Friday, April 23, 2021 3:56 PM
COMPUTER SCIENCE Page 1
pf3
pf4
pf5
pf8

Anteprima parziale del testo

Scarica SUMMARY: Computer Science - Python e più Dispense in PDF di Informatica gestionale solo su Docsity!

VON NEUMANN ARCHITECTURE

The CPU understands the machine language, which consists of 0 and 1.

PROGRAMMING

It is basically teaching a machine how to perform a certain task or solve a certain problem.

ALGORITHMS

An algorithm is a process that allows the user to solve a problem through a finite number of simple steps.

MACHINE LANGUAGE

In the Fifties, programs were all written with 0 and 1. Instructions were long sequences of bits (binary digits) and corresponded to very simple actions. Writing a very simple program required large amounts of time and extremely specialized technicians. Going through decades, programming languages have evolved towards natural language and got far from 0 and 1 alone. But even the most sophisticated language has to be translated into machine language (0/1) to be understood by the machine.

PROGRAMMING LANGUAGE

A programming language is an interface for giving a computer the instructions needed to solve a problem. Many different programming languages exist: they have different syntax, but basically do the same things and share most of the logic and rules. Programming languages enables the communication between man and machine, like natural languages do between individuals.

SOFTWARE PROGRAM

It is a sequence of statements through which a computer executes an elaboration.

Python

Friday, April 23, 2021 3:56 PM

It is a sequence of statements through which a computer executes an elaboration. The computer receives inputs and provides outputs by means of simple operations.

PYTHON

Python is a high level, interpreted, interactive, object oriented programming language. It was conceived by Guido Van Rossum in 1989 and released in 1991, with the aim to correct the defects present in other languages and to take their strengths. Since then Python has grown and has found increasing popularity, first in Web development and, especially in recent years, in the field of data science. It is an open source language, constantly improved by the developer community, and completed by several libraries. IDLE (Integrated Development and Learning Environment) is the Python programming environment, which includes two different components:

  • shell (or interpreter, or console ), which is used in the interactive mode (or "command line")
  • editor which is used in the script mode

SEQUENTIAL VS DECISION-MAKING STRUCTURE

The order in which program statements are executed hangs on a defined logical pattern, which is called control structure. So far we have been using the sequential structure only, that is a set of statements which are executed in the order they occur. Sometimes a decision making structure must be used. In this kind of structure, a certain action is performed only when specific conditions happen. In this case we can specify one or more instructions that are executed if a condition is true (and others if it is false). There are several types of decision making structures:

  • Simple decision making structure (or conditional execution, or single alternative): if
  • Alternative execution (or double alternative): if-else
  • Chained conditionals: if-elif Decision making structures are implemented in the code by conditional statements (if, else and elif).

VARIABLES

Variables are:

  • Global variable: it can be reached by any instruction in a program.
  • Local variable: it can be reached within the part of the program in which it was defined, such as a function. Name requirements: *
  • Start with a letter or _
  • No special characters
  • No reserved Python keywords
  • Upper and lower case characters are different *same for functions Note! Multiple assignment (called unpacking) is allowed.

Runtime errors indicate that there is an error in the code, even if the syntax is correct. Python shows an error message (in the shell only) indicating the part of the code that generates the error and specifying the cause. They are:

  • NameError: variable is not found
  • KeyError: key of a dictionary not found
  • ModuleNotFoundError: module not found
  • ValueError: correct data type but wrong value in a function or method
  • TypeError: wrong data type in a function or operation
  • AttributeError: wrong object or data type in a method or attribute
  • ZeroDivisionError: a number divided by 0
  • IndexError: the index>length-
  • IndentationError: when there is an incorrect indentation
  1. Semantic errors Semantic errors occur when the program is executed without producing error messages , but the results are not the correct ones they are inconsistent or not expected. They derive from a wrong code design they are also called logic errors. They are tricky to find and require a step by step re reading of the code, or the use of more sophisticated debugging tools (Debugger).

SEQUENCES

Sequences are objects that hold multiple items of data, stored one after the other. There are different types of sequences, including strings, lists and tuples. Although they have different characteristics, sequences:

  • are iterable objects
  • can be mutable or immutable
  • the position of each value is identified by a number (index) use many functions, methods and operations that allow you to access and work on the data

1. STRINGS

 A string is a sequence of characters that can contain alphanumeric characters and symbols. Strings are immutable, so we cannot change an existing string, but it’s possible to create a new string that is a variation on the original.

 Properties: indexing, chaining, slicing, traversing (NOT sorting and reassignment!)  Operations: + (concatenation), * (repetition), in (True if string in another string), is (True if identical strings)  Example:

x_string = "Milan"

2. TUPLES

 The elements of a tuple can be of any type, are comma separated and enclosed in brackets (although not necessary)  To create a tuple we can use the built in function tuple Tuples are immutable, so it is not possible to modify an existing tuple: the only possibility is to create a new tuple, variant of the original.

 Properties: indexing, chaining, slicing, traversing (NOT sorting and reassignment!)  Operations: +, *, in  Example:

x_tuple = (2, 4, 'John', 32.5, 'Rome')

3. LISTS

 A list is a sequence of values of any type, enclosed in square brackets and divided by commas  Lists are assigned to variables  A list with no elements is called an empty list  A list can be nested within another list: in this case you have to specify two indexes  To create a list it is possible to use the built in function list (useful to convert tuples into lists)

text = list("Milan") print(text) ['M', 'i', 'l', 'a', 'n']  Properties: sorting, indexing, chaining, slicing, reassignment, traversing  Operations: +, *, in  Example: x_list = [2, 4, 'John', 32.5, 'Rome']

x_list = [2, 4, 'John', 32.5, 'Rome']

DICTIONARIES

  • A dictionary is an object that contains a collection of data or items. To create a dictionary it is necessary to write in curly brackets { } the elements divided by commas (,). Every element is made of a key followed by a colon (:) and a value.
  • Alternatively you can use the dict function, which creates a new dictionary with no elements
  • Dictionaries are mutable objects
  • Properties: reassignment, traversing (NOT sorting, indexing, slicing, chaining)*
  • Operations: in (True if a KEY in in the dictionary), is (True if identical dictionaries)
  • Example:

    x_dictionary = {'ID': 'AX32D', 'Price': (10, 78, 21), 'Quantity': 1325} *we can also use functions like sum, max, min, sorted, list, tuple with dictionaries, but the elements considered are only the keys and not the corresponding values dictionary={1:'car',2:'house'} sum(dictionary) 3 Keys and values The order of items in a dictionary is unpredictable, for this reason we cannot use indexing as we can do in sequences. ○ Keys are unique and can be any kind of immutable objects. ○ Values can be any kind of object, mutable or immutable. To retrieve a value stored in the dictionary we use the corresponding key: dict_name[key1] Value To add a new key-value pair: dict_name[new_key] = new_value To change an existing key-value pair: dict_name[existing_key] = new_value PROPERTIES OF SEQUENCES AND DICTIONARIES Sorting: list Sorting means putting the element of a sequence in ascending or descending order. You can use the function sorted() or if it's a list also the method .sort() Indexing: list, tuple, string

  • The position of each element within a sequence is identified by an integer, called an index.
  • Indexing allows access to the individual elements of a sequence, using the following syntax: sequence[index]
  • To find the index knowing the element use the .index(element) method The index of the first element on the left is equal to 0 , while the index of the last element of the sequence is equal to the number of elements of the sequence minus 1.
  • It is possible to use indices with negative values: in this case the count starts from the end of the sequence. Chaining: list, tuple, string When we concatenate with the + Slicing: list, tuple, string
  • A segment or portion of a sequence is called a slice.
  • Slicing allows to select more than one element of a sequence using the syntax: sequence[start:end:step] The operation returns all the elements of the sequence from the one with the start index (included) and the one with the end index (not included).
  • Step is optional and indicates which subsequent indexes to select after the first one.
  • If start is omitted it selects the first element, if end is omitted it selects the last element. Reassignment: list and dictionary Reassigning a variable works only with mutable objects (with immutable object I can just redefine a variable) Traversing: list, tuple, string, dictionary It's the ability to pass through all the elements which are iterable

OBJECTS, INSTANCES AND THEIR CLASSES

An object is an element that can represent a value and that can perform actions. A class of objects is the collection of features of a specific type of variable.

  • Literals are elementary data types such as integers, floating points, logicals, strings, lists, tuples, dictionaries…

Overall: Hierarchies of classes

  • Superclass
  • Subclass: it inherits all data and methods of the parent class, adds more info and methods, overwrites methods.

FILE ACCESSING

  • Sequential access: the software reads the file from the beginning to the end and it can't jump from one point to another
  • Direct access: the software can jump from one point to another
  1. Open the file:

file_name = open(file,[mode]) ○ File: the path of the file (remember double \ for the path!) Mode: how to open the file  'r' read only (if file doesn't exist error)  'r+' read+write (if file doesn't exist error, if file already exists the content is NOT deleted)  'w' write (if file doesn't exist it's created, if file already exists the content is deleted)  'w+' write+read (if file doesn't exist it's created, if file already exists the content is deleted)  'a' append (if file doesn't exist it's created)  'a+' append+read (if file doesn't exist it's created)

  1. Close and save the file:

    file_name.close() File attribute

  • file.name It returns the complete path and name of the file
  • file.mode It returns the access mode with which the file was opened
  • file.closed It returns True if the file is closed, otherwise it returns False

MODULES AND LIBRARIES

  • Modules are files acting as containers, grouping useful functionalities by the topic they relate to.
  • Libraries are the place where modules can be organized. Modules installed by default with Python make up the Python standard library and they are part of the basic Python installation. ○ math ○ os (to interact with the Operating System) random (to generate random numbers)

○ random (to generate random numbers) ○ webbrowser (to open web pages in the browser) OPENPYXL To work on the entire file/workbook: excel_file = openpyxl.Workbook() It creates the Excel file excel_file with 1 sheet in the RAM (not yet on the hard disk). excel_file = openpyxl.load_workbook('file.xlsx') It creates a new object excel_file that contains everything of the existing file file.xlsx saved in the working directory excel_file.save('file.xlsx') It saves the excel_file object in the file.xlsx file located in the working directory To work on the sheets of the file: new_sheet = excel_file['excel_sheet'] It creates the new_sheet worksheet object by copying the contents of the excel_sheet worksheet which is in the excel_file file excel_file['Student list'] It makes the "Student list" sheet the active one excel_file.active.title = 'Student list' It renames the active sheet in the excel_file file as "Student list" excel_file.create_sheet('Student list' [,n]) It creates a new sheet called "Student list" in excel_file file, inserting it by default at the end Using ('Student list', n) the new sheet is inserted at position n (where n is a number, starting from 0 as first position) excel_file.sheetnames It returns the list of all the names of the sheets in the excel_file file To work on the cells of the sheet: excel_file['excel_sheet']['A1'] = 'Hi guys' It writes 'Hi guys' in cell A1 of excel_sheet sheet of the excel_file file excel_sheet.cell(x=5, y=2).value It gives access to the value stored in B5 cell of the excel_sheet sheet X = row (5) Y = column (B) Formatting a cell: excel_file['A1'].fill = openpyxl.styles.PatternFill(fill_type = 'solid', start_color = openpyxl.styles.colors.BLUE) excel_file['A1'].font = openpyxl.styles.Font(italic = True, bold = True, color = openpyxl.styles.colors.WHITE) excel_file['A1'].alignment = openpyxl.styles.Alignment(horizontal = 'center')