Fondamenti della Conversione di Tipo
La conversione di tipo consente di passare tra i tipi fondamentali di Python, così i valori possono essere confrontati, calcolati o visualizzati.
Conversione a int
int(x) crea un intero.
- Da un int: restituisce lo stesso numero;
- Da un float: tronca verso zero (ad esempio,
int(2.9)restituisce2,int(-2.9)restituisce-2); - Da una stringa: la stringa deve rappresentare un intero (spazi opzionali e segno sono accettati).
Conversioni valide
12345678910# Converting different types of user input to integers age_input = " 42 " temperature_reading = 2.9 negative_balance = -2.9 print(int(age_input)) # 42 → clean string converted to int print(int(temperature_reading)) # 2 → fractional part truncated print(int(negative_balance)) # -2 → also truncates toward zero print(int("7")) # 7 → string number becomes integer print(int(" -15 ")) # -15 → handles spaces and sign
Questi generano ValueError
12int("2.5") # ValueError - not an integer string int("42a") # ValueError
Conversione a float
float(x) crea un numero a virgola mobile.
- Funziona per interi e stringhe in notazione decimale o scientifica;
- Le virgole non sono punti decimali in Python.
Conversioni valide
12345678# Converting numeric inputs for a shopping calculator quantity = 3 price_str = "2.5" discount_factor = "1e3" # scientific notation for 1000 print(float(quantity)) # 3.0 → integer converted to float print(float(price_str)) # 2.5 → string price converted to float print(float(discount_factor)) # 1000.0 → converts from scientific notation
Questi generano ValueError
1float("2,5") # ValueError - use a dot, not a comma
Conversione a str
str(x) crea una rappresentazione in formato stringa leggibile dall'uomo. Preferire gli f-string quando si costruiscono messaggi.
12345678910# Formatting a student's exam result student_age = 42 average_score = 3.5 print(str(student_age)) # "42" → number converted to string print(str(average_score)) # "3.5" → float converted to string student_name, final_score = "Ada", 98 report_message = f"{student_name} scored {final_score} points on the exam." print(report_message)
Conversione a bool
bool(x) segue le regole di veridicità di Python.
- Numeri:
0èFalse, qualsiasi altro numero èTrue; - Stringhe:
""(vuota) èFalse, qualsiasi stringa non vuota èTrue(anche"0"e"False").
123456789101112# Checking how different user inputs behave as boolean values login_attempts = 0 notifications = 7 username = "" user_id = "0" status = "False" print(bool(login_attempts)) # False → 0 means no attempts yet print(bool(notifications)) # True → non-zero means new notifications print(bool(username)) # False → empty string means no username entered print(bool(user_id)) # True → any non-empty string is truthy print(bool(status)) # True → text "False" is still a non-empty string
Errori da evitare
int("2.5")generaValueError- analizzare prima comefloat(), poi troncare o arrotondare;- Abitudine locale:
"2,5"non è valido - usare"2.5"; - Underscore nelle stringhe di input:
"1_000"non è valido - rimuovere prima gli underscore:"1_000".replace("_", ""); - Sorpresa nella veridicità:
bool("0")èTrue- confrontare esplicitamente il contenuto della stringa se necessario, ad esempios == "0".
1. Cosa produce ciascuna riga?
2. Quale chiamata genera un ValueError?
3. Seleziona l'affermazione corretta.
Grazie per i tuoi commenti!
Chieda ad AI
Chieda ad AI
Chieda pure quello che desidera o provi una delle domande suggerite per iniziare la nostra conversazione
Fantastico!
Completion tasso migliorato a 5.26
Fondamenti della Conversione di Tipo
Scorri per mostrare il menu
La conversione di tipo consente di passare tra i tipi fondamentali di Python, così i valori possono essere confrontati, calcolati o visualizzati.
Conversione a int
int(x) crea un intero.
- Da un int: restituisce lo stesso numero;
- Da un float: tronca verso zero (ad esempio,
int(2.9)restituisce2,int(-2.9)restituisce-2); - Da una stringa: la stringa deve rappresentare un intero (spazi opzionali e segno sono accettati).
Conversioni valide
12345678910# Converting different types of user input to integers age_input = " 42 " temperature_reading = 2.9 negative_balance = -2.9 print(int(age_input)) # 42 → clean string converted to int print(int(temperature_reading)) # 2 → fractional part truncated print(int(negative_balance)) # -2 → also truncates toward zero print(int("7")) # 7 → string number becomes integer print(int(" -15 ")) # -15 → handles spaces and sign
Questi generano ValueError
12int("2.5") # ValueError - not an integer string int("42a") # ValueError
Conversione a float
float(x) crea un numero a virgola mobile.
- Funziona per interi e stringhe in notazione decimale o scientifica;
- Le virgole non sono punti decimali in Python.
Conversioni valide
12345678# Converting numeric inputs for a shopping calculator quantity = 3 price_str = "2.5" discount_factor = "1e3" # scientific notation for 1000 print(float(quantity)) # 3.0 → integer converted to float print(float(price_str)) # 2.5 → string price converted to float print(float(discount_factor)) # 1000.0 → converts from scientific notation
Questi generano ValueError
1float("2,5") # ValueError - use a dot, not a comma
Conversione a str
str(x) crea una rappresentazione in formato stringa leggibile dall'uomo. Preferire gli f-string quando si costruiscono messaggi.
12345678910# Formatting a student's exam result student_age = 42 average_score = 3.5 print(str(student_age)) # "42" → number converted to string print(str(average_score)) # "3.5" → float converted to string student_name, final_score = "Ada", 98 report_message = f"{student_name} scored {final_score} points on the exam." print(report_message)
Conversione a bool
bool(x) segue le regole di veridicità di Python.
- Numeri:
0èFalse, qualsiasi altro numero èTrue; - Stringhe:
""(vuota) èFalse, qualsiasi stringa non vuota èTrue(anche"0"e"False").
123456789101112# Checking how different user inputs behave as boolean values login_attempts = 0 notifications = 7 username = "" user_id = "0" status = "False" print(bool(login_attempts)) # False → 0 means no attempts yet print(bool(notifications)) # True → non-zero means new notifications print(bool(username)) # False → empty string means no username entered print(bool(user_id)) # True → any non-empty string is truthy print(bool(status)) # True → text "False" is still a non-empty string
Errori da evitare
int("2.5")generaValueError- analizzare prima comefloat(), poi troncare o arrotondare;- Abitudine locale:
"2,5"non è valido - usare"2.5"; - Underscore nelle stringhe di input:
"1_000"non è valido - rimuovere prima gli underscore:"1_000".replace("_", ""); - Sorpresa nella veridicità:
bool("0")èTrue- confrontare esplicitamente il contenuto della stringa se necessario, ad esempios == "0".
1. Cosa produce ciascuna riga?
2. Quale chiamata genera un ValueError?
3. Seleziona l'affermazione corretta.
Grazie per i tuoi commenti!