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


Introduzione alla programmazione in Python: Variabili, Tipi di Dati, Operatori e Moduli, Schemi e mappe concettuali di Informatica

Documento scritto da me in inglese. Tratta gli argomenti principali per imparare a programmare in python. Non c'è necessità di conoscere già un linguaggio di programmazione. Gli argomenti principali su come programmare vengono affrontati direttamente nel testo. Ogni argomento viene spiegato e affiancato a degli esempi. Esercizi svolti sono inclusi per vedere i concetti spiegati in un contesto pratico. Gli argomenti inclusi sono: What is the meaning of Programming? What is Python? Which kind of Python files exist? Where can I program in Python? How can I set-up Python on my computer? Input/Output Comments Variables Data Types Modules Random Conditionals Loops Lists Dictionaries Sets Tuples Casting Functions Variable Scopes Classes Inheritance and Polymorphism Debug suggestions

Tipologia: Schemi e mappe concettuali

2023/2024

In vendita dal 02/06/2024

giulio_russo
giulio_russo 🇮🇹

4.8

(42)

111 documenti

1 / 86

Toggle sidebar

Questa pagina non è visibile nell’anteprima

Non perderti parti importanti!

bg1
🐍
Python
💻
programming
pf3
pf4
pf5
pf8
pf9
pfa
pfd
pfe
pff
pf12
pf13
pf14
pf15
pf16
pf17
pf18
pf19
pf1a
pf1b
pf1c
pf1d
pf1e
pf1f
pf20
pf21
pf22
pf23
pf24
pf25
pf26
pf27
pf28
pf29
pf2a
pf2b
pf2c
pf2d
pf2e
pf2f
pf30
pf31
pf32
pf33
pf34
pf35
pf36
pf37
pf38
pf39
pf3a
pf3b
pf3c
pf3d
pf3e
pf3f
pf40
pf41
pf42
pf43
pf44
pf45
pf46
pf47
pf48
pf49
pf4a
pf4b
pf4c
pf4d
pf4e
pf4f
pf50
pf51
pf52
pf53
pf54
pf55
pf56

Anteprima parziale del testo

Scarica Introduzione alla programmazione in Python: Variabili, Tipi di Dati, Operatori e Moduli e più Schemi e mappe concettuali in PDF di Informatica solo su Docsity!

Python

programming

Index

  • What is the meaning of Programming?
  • What is Python?
  • Which kind of Python files exist?
  • Where can I program in Python?
  • How can I set-up Python on my computer?
  • Input/Output
  • Comments
  • Variables
  • Data Types
  • Casting
  • Modules
  • Random
  • Conditionals
  • Loops
  • Exercises
  • Lists
  • Dictionaries
  • Exercises
  • Sets
  • Tuples
  • Casting
  • Exercise
  • Functions
  • Variable Scopes
  • Exercise
  • Classes
  • Inheritance and Polymorphism
  • Exercise
  • Debug suggestions
  • Thanks

What is Python?

Python is a programming language that is:

  • INTERPRETED: it doesn’t need to be compiled from the computer (directly all the code is translated into machine code) but it is translated and executed line by line on the fly from the Python Virtual Machine. While it is not as fast as lower-level languages (like C or C++), it offers good performance for most applications.
  • MULTI-PARADIGM: Python supports multiple programming paradigms, including procedural, object-oriented, and functional programming.
  • CROSS-PLATFORM: Python is cross-platform, meaning it can run on various operating systems like Windows, macOS, and Linux without modification. It is based on:
  1. Script: a sequence of instructions that can be executed. This will be the starting point of our Python code. It is a file with ‘.py' extension.
  2. Module: file containing Python code (it can define functions, classes, variables etc.) that can be reused in other Python scripts. Modules allow you to organize your code into logical units and facilitate code reuse and maintenance.
  3. Package: directory that contains one or more modules. They provide a hierarchical structure for organizing and distributing Python code. They allow you to group related modules together and make it easier to manage large codebases. In order to run, it needs:
  4. Interpreter: the program that reads and executes Python code. It translates Python code into intermediate bytecode instructions, which are then executed by the Python Virtual Machine (PVM).
  5. Virtual Environment: self-contained directory that contains a specific version of Python interpreter and its associated modules and packages. It allows you to create isolated environments for your Python projects, each with its own dependencies and configurations. Virtual environments are useful for managing dependencies, avoiding conflicts between different projects, and ensuring reproducibility of software environments. Python has its syntax that has to be understood in order to write a code that is interpretable.

Where can I program in Python?

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”:

  • replit.com allows to program in several languages online without any installation
  • colab.research.google.com is provided by Google and offers a lot of advanced functionalities for Python programming and works with Python notebooks. I personally suggest to start with replit.com if you have never programed in your life. Its enough to reproduce the code you will see in this book and study the proposed exercises. If you have a little bit of experience you can try to use colab.research.google.com to improve your knowledge about Python programming systems!

Which kind of Python files exist?

Python code have to be written on files in order to be executed. Two kind of python file exist:

  • ‘.py’ files: simple Python files that can contain python code. These are the ones we will use in our book to reproduce our exercises. We just need to write code and launch our script! This can be done using our IDE, or inside the Terminal with: python3 FILE.py - ‘.ipynb’ files: called “Python notebook file”, are files that contains blocks of Python code and markdown code (a language that is used to write normal text). This could be helpful in order to execute one piece of code at time and bring some explanations of what we are coding.

How can I set-up Python on my computer?

  1. Python installation: As we have mentioned before, we need a Python interpreter. Where can we find it? On python.org you can find the Python interpreter installer for every operating systems. Follow the instructions on the site and you will install the Python interpreter on your computer! At the moment of the writing of this book the latest major Python version is 3.x. Here comes a big difference:
  • Windows computers do NOT have native python installed.
  • Linux and macOS computers HAVE native python installed. We can localize the active interpreter using some Terminal commands:

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.

Input/Output

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 ‘’’

Comments

Variables

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:

  • Camel case: you start writing the name in lower case. If the name contains more than one word, the words following the first one are written with the first letter capitalized: userName = ...
  • Snake case: you start the name in lower case. If the name contains more than one word, subsequent words are also written in lower case, using the underscore. user_name = ...
  • Kebab case: is similar to snake case, but a hyphen (-) is used. user-name = ...
  • Pascal case: begin with a capital letter. If the name contains multiple words, all words begin with a capital letter. UserName = ... Variable names can’t start with a number, but they can contain it:

    1variable variable and are case sensitive (lower or higher case letter matter): A a # different variable because it’s lower case

  • F-strings allow to insert in an intuitive way the variables inside our string by placing the string variables we want to print, between curly brackets, in the place we want to print it. Also, we have to add an ‘f’ before the quotation marks:

    weather = input(“How is the weather today?”) print(f“Today is {weather}”) output: How is the weather today? ▋Cloudy Today is Cloudy

  • Format function allows to build our string and leave curly brackets in the place we will add some string values. At the end of the quotation marks we add ‘.format’ and specify in brackets the string values we want to add into the string. This follow a positional order: STRING .format( VALUES )

    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

  • Digits formatting: allows to format numbers. STRING. zfill( LEN ) The string is filled with zeros “0” until the desired length LEN is reached:

    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.

  • Access single characters: a string is by definition a sequence of characters. Every character can be accessed using an index value, starting the count from zero: character = STRING [ INDEX ] “Hello” is seen as: H e l l o 0 1 2 3 4

    print(“Hello”[0]) output: H If you try to access with an index that doesn’t exists, we get an IndexError.

  • Special characters: Strings can be formatted using special characters like ‘ ‘: space, ‘\n’: new line, ‘\t’: tab, ‘\r’: carriage return
  • Print trick: we can use some parameters of the print function. print( OUTPUT1 , OUTPUT2 , ..., sep= SEPARATOR , end= END ) OUTPUT1, OUTPUT2, ...: any content we want to print, SEPARATOR: what we use to divide the content we print. Default is space ‘ ‘, END: what to print at the end of the contents. Default is new line ‘\n’.

    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.

  • Convert to lower or to upper case the string: this can be done using: STRING .lower() and STRING .upper()

    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

  • Length: the length of a string can be obtained with: len( STRING )

    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:

  • 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: 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:

  • +: sum

    print(3+2) output: 5

  • -: subtraction

    print(3-2) output: 1

  • *: product

    print(3*2) output: 6

  • /: division

    print(3/2) # based on the values, we can have an integer or a float number output: 1.

  • /=: divide the right value by the left value and store the result in the left.

    a = 3 b = 2 a /= b # a = a / b = 3 / 2 = 1. print(a) output: 1.

  • %=: evaluate the remainder of the division of the left value divided by the right 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 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 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.

  • !=: check the inequality between two variables.

    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