














































































Studia grazie alle numerose risorse presenti su Docsity
Guadagna punti aiutando altri studenti oppure acquistali con un piano Premium
Prepara i tuoi esami
Studia grazie alle numerose risorse presenti su Docsity
Prepara i tuoi esami con i documenti condivisi da studenti come te su Docsity
Trova i documenti specifici per gli esami della tua università
Preparati con lezioni e prove svolte basate sui programmi universitari!
Rispondi a reali domande d’esame e scopri la tua preparazione
Riassumi i tuoi documenti, fagli domande, convertili in quiz e mappe concettuali
Studia con prove svolte, tesine e consigli utili
Togliti ogni dubbio leggendo le risposte alle domande fatte da altri studenti come te
Esplora i documenti più scaricati per gli argomenti di studio più popolari
Ottieni i punti per scaricare
Guadagna punti aiutando altri studenti oppure acquistali con un piano Premium
Documento scritto da me in inglese sul linguaggio Python. La dispensa spiega le basi del linguaggio e la sua sintassi in maniera chiara e semplice. Si parte dalle funzioni di input output fino ai principali tipi di dato, strutture di controllo e classi. Un tutorial tecnico è incluso per poter eseguire codici Python in maniera autonoma. Ogni argomento è corredato di esercizi svolti per comprendere meglio gli argomenti. Questo documento è adatto per chiunque indipendentemente dall'università/corso voglia approfondire la programmazione Python in maniera strutturata e completa.
Tipologia: Dispense
1 / 86
Questa pagina non è visibile nell’anteprima
Non perderti parti importanti!















































































Python is a programming language that is:
Before delving in deep into Python set up, are there any places where I can program in Python ready to go? Yes. A lot of solutions exist to program in Python “online”:
Python code have to be written on files in order to be executed. Two kind of python file exist:
For this reason, in Python we can create the ‘Virtual environments’: places where our Python interpreter and packages are “protected” from the outside. Is it a good idea? well, it depends. If you have to work on a lot of little projects maybe it could be a waste of time reinstall every time all the packages, and also they occupy memory on your computer! In this case it is convenient to work with our general Python interpreter and install one time the packages we need. If we have special need to work with specific packages versions, we can create the “virtual environment”, a place where we create an isolated Python interpreter (different from the general one) and after activating it, we can install the specific packages we need. We can run our code by selecting before the created interpreter and we are ready to go! The commands to create a virtual environment called “myvenv” are: python3 -m venv PATH_TO_YOUR_PROJECT /myvenv Some folders will be created insider your project folder. We can activate the created “myvenv” with: source PATH_TO_YOUR_PROJECT /myvenv/bin/activate Now in the Terminal we will see in round brackets the name of our virtual environment: (myvenv) user@computer ~ % Only when the environment is activated, we can install the packages in the same way we have seen before and run our code. Now we are sure that our packages will be installed inside the activated environment and the code we execute will use the activated environment. If we check the packages with ‘pip3 list’ we will see the packages installed only in this environment. In this way it is a “protected area”. If the environment is not activated the packages we will install will go inside the outer Python interpreter (/usr/local/bin) and this will be the interpreter we will use to run our code. Finally, we can deactivate the environment: deactivate and the environment name will disappear in the Terminal. In PyCharm you can choose to create a virtual environment specific for your project (this will be done automatically) or you can choose another interpreter (by selecting for example the /usr/local/bin/python3 or any other environment you have created). In Visual Studio Code you don’t have any option to create automatically an environment specific for your project. You have to create your virtual environment as you have seen before, and then select it from the IDE. Of course you can select also the /usr/local/bin/python3 if you don’t want to use a specific environment. Another option that I encourage you to explore are the Environment managers like Anaconda, or its lighter version Miniconda. These are softwares that helps you to manage your environment in an easiest way. More on: anaconda.com/download or docs.anaconda.com/free/miniconda.
The most simple thing you can think to do while using a programming language is input and output any data. ⏫ Output is simply done with: print( OUTPUT ) where the content we put inside the brackets will be show on the terminal window. For example, we can show some text! We just need to place the content we want to print inside the quotation marks “”.
print(“Hello world!”) output: Hello world! We can exchange the functionality of the quotation marks with the apexes: print(‘Hello world!’) output: Hello world! This become useful if we need to print something inside quotation marks or apexes: print(‘Hello “world”!’) output: Hello “world”! print(“Hello ‘world’!”) output: Hello ‘world’! This is necessary because if we use nested quotation marks, the print function will not understand the output we want to print: print(“Hello “world”!”) This will return a Syntax Error : Python understand that the content “Hello “ is the one we want to print. The first quotation mark around “world” stop the interpreted content to print. Then we place some text out of the quotation marks, but this is not a valid syntax for the print function, that accepts only the entire output between quotation marks.
Comments are pieces of text ignored by the Interpreter. They are preceded by the symbol ‘#’, so anything after this symbol on the same line is interpreted as a comment. It can be placed in any part of the code. We can use them to include useful explanations of our code in human language. They become very important if we have to read our code after a long time. Implementation details can be forgotten or not really clear without a clear human explanation. Comments are here for that:
print(“Goodbye”) # say goodbye at the end of the code In case of big comments we can wrap it between three quotation marks or three apexes: “”” This is a comment on more rows “”” ‘’’ Also this is a comment on more rows ‘’’
We need to store in our memory (the RAM) the information that we use in our code. This is achieved with variables: we give a name to a piece of memory that will contain our data, and we will use that name to use the data every time we need: VARIABLE_NAME = VALUE The symbol ‘=‘ act as assignment symbol: the VALUE is stored inside the variable with name VARIABLE_NAME. In Python a variable is created in the moment you first assign its value, and its type is identified based on the value assigned. In this way, Python is a non-typed language. If we assign a value to a variable, and we do again the assignment with a new value, we lose the previous variable value and the variable will contain the new value assigned. Also, in Python the assignment symbol can be used also to do multiple assignments at the same time: VARIABLE_NAME1 , VARIABLE_NAME2 = VALUE1 , VALUE It is a good standard to give meaningful names to the variables based on the data they represent. Different method to name the variables exists:
1variable variable and are case sensitive (lower or higher case letter matter): A a # different variable because it’s lower case
weather = input(“How is the weather today?”) print(f“Today is {weather}”) output: How is the weather today? ▋Cloudy Today is Cloudy
weather = input(“How is the weather today?”) temperature = input(“How is the temperature today?”) print(“Today is {} and {}”.format(weather, temperature)) # weather corresponds to to the first curly brackets, while temperature to the second output: How is the weather today? ▋Cloudy How is the temperature today? ▋Cold Today is Cloudy and Cold
number = “7” filled_number = number.zfill(10) print(filled_number) output: 0000000007
Manipulation: Strings can be manipulated in many different ways. It means we can access and modify the entire string or just some characters.
print(“Hello”[0]) output: H If you try to access with an index that doesn’t exists, we get an IndexError.
print(“First item”, “Second item”, sep=“-“, end=“”) print(“_Third item”) output: First item-Second item_Third item By using “-“ separator, the items in the first print are separated with the dash. With end “” we do not apply the default “\n”, thus the following print go directly after the first without going on the new line.
print(“HELLO”.lower()) print(“hello”.upper()) output: hello HELLO We can capitalize our string: STRING .capitalize() print(“giulio”.capitalize()) output: Giulio We can merge these two functions into one: set all the string to lower and capitalize the result: STRING .title() print(“GiULiO”.title()) output: Giulio
print(len(“Hello”)) output: 5
Integer : integer numbers. We define an integer variable with the assignment of an integer number (without using any quotation marks or apexes):
number = 7 print(number) output: 7 Float : floating digits number. We define a float variable with the assignment of a float number: pi = 3. print(pi) output: 3. Complex : complexes number. “j” is the letter used to identify imaginary parts. Real and Imaginary parts can be accessed with .real and .imagine functions: z = 3 + 2j print(z, z.real, z.imag) output: 3 + 2j
Formatting:
big_integer = 123_456_ big_float = 123_456_789. print(big_integer, big_float) output: 123456789 123456789. It is possible to improve the print using colon and specify after the desired separator: VARIABLE:SEPARATOR >>> number = 2000000000 >>> print(f”{number:,}”) # using “,” separator output: 2,000,000, In case of needing power of 10, we can use the “e” followed by the 10th power: >>> print(5e3) # 5 * 10^ output: 5e
print(10/3) output: 3. They can be formatted inside an F-string using: VARIABLE :. DIGITS f VARIABLE is rounded to DIGITS digits: division = 10/ print(f”{division:.2f}”) # limit to two digits output: 3. Digits can be also rounded with round function: pi = 3. >>> print(pi) output: 3. Complex : complexes number. “j” is the letter used to identify imaginary parts. Real and Imaginary parts can be accessed with .real and .imagine functions: >>> z = 3 + 2j >>> print(z, z.real, z.imag) output: 3 + 2j 3. 2. Formatting: - Long numbers: In case of really long numbers, we can format them using underscores to improve the visualization of the number, but it doesn’t affect the value of it: >>> big_integer = 123_456_ >>> big_float = 123_456_789. >>> print(big_integer, big_float) output: 123456789 123456789. It is possible to improve the print using colon and specify after the desired separator: VARIABLE:SEPARATOR >>> number = 2000000000 >>> print(f”{number:,}”) # using “,” separator output: 2,000,000, In case of needing power of 10, we can use the “e” followed by the 10th power: >>> print(5e3) # 5 * 10^ output: 5e - Digits: formatting the float digits is very useful in a lot of cases. As default, this is not implemented: >>> print(10/3) output: 3. They can be formatted inside an F-string using: VARIABLE :. DIGITS f VARIABLE is rounded to DIGITS digits: >>> division = 10/ >>> print(f”{division:.2f}”) # limit to two digits output: 3. Digits can be also rounded with round function: round( VARIABLE , DIGITS ) number1 = round(10/3, 2) # 10/3 = 3.33333333 -> 3. number2 = round(2/3, 3) # 2/3 = 0.666666667 -> 0.
Operators: integer and float number can be used with several mathematical operators. They can be used between variables but also directly in print statements:
print(3+2) output: 5
print(3-2) output: 1
print(3*2) output: 6
print(3/2) # based on the values, we can have an integer or a float number output: 1.
a = 3 b = 2 a /= b # a = a / b = 3 / 2 = 1. print(a) output: 1.
a = 3 b = 2 a %= b # a = a % b = 3 % 2 = 1 print(a) output: 1
a = 3 b = 2 a //= b # a = a // b = 3 // 2 = 1 print(a) output: 1
a = 3 b = 2 a **= b # a = a ** b = 3 ** 2 = 9 print(a) output: 9 Functions: Python offer some built in functions that work with numbers.
print(abs(-4)) output: 4
print(pow(3, 2, 3)) # 3 ** 2 % 3 = 9 % 3 = 0 output: 0
Boolean : a Boolean variable can have only two values, True or False. It represents a logical result:
condition1 = True condition2 = False print(condition1, condition2) output: True False But how we can use and obtain a variable like this? Using boolean operators:
Comparison operators: operators that perform comparisons between values.
number1 = 123 number2 = 123 print(number1 == number2)
a %= b # a = a % b = 3 % 2 = 1 >>> print(a) output: 1 - //=: do floor division of the right value by the left value and store the result in the left variable. >>> a = 3 >>> b = 2 >>> a //= b # a = a // b = 3 // 2 = 1 >>> print(a) output: 1 - **=: do the power of the right value to the left value and store the result in the left variable. >>> a = 3 >>> b = 2 >>> a **= b # a = a ** b = 3 ** 2 = 9 >>> print(a) output: 9 Functions: Python offer some built in functions that work with numbers. - abs(): return the absolute value of the input. abs( NUMBER ) >>> print(abs(-4)) output: 4 - pow(): return the power of a base to the exponent with some more customization: pow( BASE , EXPONENT , MODULE ) >>> print(pow(3, 2, 3)) # 3 ** 2 % 3 = 9 % 3 = 0 output: 0 Boolean : a Boolean variable can have only two values, True or False. It represents a logical result: >>> condition1 = True >>> condition2 = False >>> print(condition1, condition2) output: True False But how we can use and obtain a variable like this? Using boolean operators: Comparison operators: operators that perform comparisons between values. - ==: check the equality between two variables. >>> number1 = 123 >>> number2 = 123 >>> print(number1 == number2) output: True This works with all the data types we have seen, also strings: string1 = “Hello” string2 = “hello” print(string1 == string2) # return False because string1 have capital “H”, while string2 no output: False print(a) output: 1 - **=: do the power of the right value to the left value and store the result in the left variable. >>> a = 3 >>> b = 2 >>> a **= b # a = a ** b = 3 ** 2 = 9 >>> print(a) output: 9 Functions: Python offer some built in functions that work with numbers. - abs(): return the absolute value of the input. abs( NUMBER ) >>> print(abs(-4)) output: 4 - pow(): return the power of a base to the exponent with some more customization: pow( BASE , EXPONENT , MODULE ) >>> print(pow(3, 2, 3)) # 3 ** 2 % 3 = 9 % 3 = 0 output: 0 Boolean : a Boolean variable can have only two values, True or False. It represents a logical result: >>> condition1 = True >>> condition2 = False >>> print(condition1, condition2) output: True False But how we can use and obtain a variable like this? Using boolean operators: Comparison operators: operators that perform comparisons between values. - ==: check the equality between two variables. >>> number1 = 123 >>> number2 = 123 >>> print(number1 == number2) output: True This works with all the data types we have seen, also strings: >>> string1 = “Hello” >>> string2 = “hello” >>> print(string1 == string2) # return False because string1 have capital “H”, while string2 no output: False It’s important to highlight the difference between this symbol “==“ and “=“. The assignment symbol “=“ assign the right valute to the left variable, thus, it performs a basic action of Python, while the equality symbol “==“ is a comparison operator that return a boolean value. Despite their similarities, they do completely different jobs.
number1 = 123 number2 = 123 print(number1 != number2) output: False This works with all the data types we have seen, also strings: letter1 = “Hello” letter2 = “hello” print(letter1 != letter2) # return True because letter1 and letter2 are actually different due to the capital “H” output: True