Tipi di dati in Python
Versione italiana
1. Variabili e tipi di dati
In Python, una variabile è un contenitore per memorizzare dati. Non è necessario dichiarare esplicitamente il tipo di una variabile (Python è dinamicamente tipizzato), il che significa che il tipo viene determinato automaticamente in base al valore assegnato.
Numeri
Python supporta diversi tipi di numeri:
- Interi (
int
): Numeri senza decimali, come5
,-3
,1000
. - Float (
float
): Numeri con decimali, come3.14
,-0.001
,2.0
. - Complessi (
complex
): Numeri con una parte reale e una immaginaria, come2 + 3j
.
Esempi:
x = 10 # Intero
y = 3.14 # Float
z = 2 + 3j # Complesso
Stringhe (str
)
Le stringhe sono sequenze di caratteri, racchiuse tra singoli (' '
) o doppi (" "
) apici. Python offre molte operazioni e metodi per lavorare con le stringhe:
- Concatenazione: Unire due stringhe con
+
. - Formattazione: Inserire variabili in una stringa usando
f-string
(da Python 3.6 in poi). - Metodi: Come
upper()
,lower()
,strip()
,split()
, ecc.
Esempi:
nome = "Alice"
messaggio = f"Ciao, {nome}!" # Formattazione con f-string
print(messaggio.upper()) # Stampa "CIAO, ALICE!"
Booleani (bool
)
I booleani rappresentano valori di verità: True
(vero) o False
(falso). Sono spesso usati nelle condizioni e nei controlli di flusso.
Esempio:
is_python_fun = True
if is_python_fun:
print("Python è divertente!")
2. Input e output
Funzione print()
La funzione print()
viene utilizzata per stampare messaggi o valori sullo schermo. Puoi passarle più argomenti, separati da virgole.
Esempi:
print("Ciao, mondo!") # Stampa una stringa
print("Il valore di x è:", x) # Stampa una stringa e una variabile
Funzione input()
La funzione input()
permette di ricevere input dall'utente. Restituisce sempre una stringa, quindi è necessario convertire il valore se si desidera un numero.
Esempio:
nome = input("Come ti chiami? ")
print(f"Ciao, {nome}!")
Se vuoi ricevere un numero:
eta = int(input("Quanti anni hai? ")) # Converte l'input in un intero
3. Operatori
Gli operatori sono simboli speciali che eseguono operazioni su variabili e valori.
Operatori aritmetici
+
(addizione),-
(sottrazione),*
(moltiplicazione),/
(divisione)//
(divisione intera),%
(modulo, resto della divisione),**
(elevamento a potenza)
Esempi:
a = 10
b = 3
print(a + b) # 13
print(a // b) # 3 (divisione intera)
print(a ** b) # 1000 (10 elevato alla 3)
Operatori di confronto
==
(uguale),!=
(diverso),>
(maggiore),<
(minore),>=
(maggiore o uguale),<=
(minore o uguale)
Esempi:
print(a == b) # False
print(a > b) # True
Operatori logici
and
(e),or
(o),not
(non)
Esempi:
print(a > 5 and b < 5) # True
print(not a == b) # True
Operatori di assegnazione
=
(assegnazione),+=
,-=
,*=
,/=
(assegnazione con operazione)
Esempi:
x = 5
x += 3 # Equivale a x = x + 3
print(x) # 8
4. Commenti e documentazione del codice
I commenti sono note nel codice che non vengono eseguite. Servono per spiegare il funzionamento del codice o per disabilitare temporaneamente una parte di esso.
- Commento su una riga: Usa
#
. - Commento su più righe: Usa
""" ... """
o''' ... '''
.
Esempi:
# Questo è un commento su una riga
x = 10 # Assegna 10 a x
"""
Questo è un commento
su più righe.
"""
Documentazione del codice
In Python, puoi documentare funzioni, classi o moduli usando docstring, che sono stringhe di documentazione racchiuse tra """ ... """
. Queste vengono visualizzate quando usi la funzione help()
.
Esempio:
def somma(a, b):
"""
Questa funzione somma due numeri.
:param a: Primo numero
:param b: Secondo numero
:return: La somma di a e b
"""
return a + b
help(somma) # Mostra la documentazione della funzione
English version
Data Types in Python
1. Variables and Data Types
In Python, a variable is a container for storing data. You don't need to explicitly declare the type of a variable (Python is dynamically typed), which means that the type is determined automatically based on the value assigned to it.
Numbers
Python supports several types of numbers:
- Integers (
int
): Numbers without decimals, such as5
,-3
,1000
. - Floats (
float
): Numbers with decimals, such as3.14
,-0.001
,2.0
. - Complexes (
complex
): Numbers with a real and an imaginary part, such as2 + 3j
.
Examples:
x = 10 # Integer
y = 3.14 # Float
z = 2 + 3j # Complex
Strings (str
)
Strings are sequences of characters, enclosed in single (' '
) or double (" "
) quotes. Python provides many operations and methods for working with strings:
- Concatenation: Join two strings with
+
. - Formatting: Insert variables into a string using
f-string
(Python 3.6 and later). - Methods: Like
upper()
,lower()
,strip()
,split()
, etc.
Examples:
name = "Alice"
message = f"Hello, {name}!" # Formatting with f-string
print(message.upper()) # Prints "HELLO, ALICE!"
Booleans (bool
)
Booleans represent truth values: True
or False
. They are often used in conditions and flow controls.
Example:
is_python_fun = True
if is_python_fun:
print("Python is fun!")
2. Input and Output
print()
Function
The print()
function is used to print messages or values to the screen. You can pass it multiple arguments, separated by commas.
Examples:
print("Hello, world!") # Prints a string
print("The value of x is:", x) # Prints a string and a variable
input()
function
The input()
function allows you to receive input from the user. It always returns a string, so you need to convert the value if you want a number.
Example:
name = input("What's your name? ")
print(f"Hello, {name}!")
If you want to receive a number:
age = int(input("How old are you? ")) # Converts the input to an integer
3. Operators
Operators are special symbols that perform operations on variables and values.
Arithmetic Operators
+
(addition),-
(subtraction),*
(multiplication),/
(division)//
(integer division),%
(modulo, remainder of division),**
(exponentiation)
Examples:
a = 10
b = 3
print(a + b) # 13
print(a // b) # 3 (integer division)
print(a ** b) # 1000 (10 to the power of 3)
Comparison Operators
==
(equal),!=
(not equal),>
(greater than),<
(less than),>=
(greater than or equal),<=
(less than or equal)
Examples:
print(a == b) # False
print(a > b) # True
Logical operators
and
(and),or
(or),not
(not)
Examples:
print(a > 5 and b < 5) # True
print(not a == b) # True
Assignment operators
=
(assignment),+=
,-=
,*=
,/=
(assignment with operation)
Examples:
x = 5
x += 3 # Equivalent to x = x + 3
print(x) # 8
4. Comments and code documentation
Comments are notes in the code that are not executed. They are used to explain how the code works or to temporarily disable a part of it.
- Single-line comment: Use
#
. - Multiple-line comment: Use
""" ... """
or''' ... '''
.
Examples:
# This is a single-line comment
x = 10 # Assign 10 to x
"""
This is a multi-line comment.
"""
Code documentation
In Python, you can document functions, classes, or modules using docstrings, which are documentation strings enclosed in """ ... """
. These are displayed when you use the help()
function.
Example:
def sum(a, b):
"""
This function adds two numbers.
:param a: First number
:param b: Second number
:return: The sum of a and b
"""
return a + b
help(sum) # Show documentation for the function
Commenti
Posta un commento