Notice: This page requires JavaScript to function properly.
Please enable JavaScript in your browser settings or update your browser.
Impara Fondamenti della Conversione di Tipo | Interazioni tra Tipi Diversi
Tipi di Dati in Python

bookFondamenti 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) restituisce 2, 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
copy

Questi generano ValueError

12
int("2.5") # ValueError - not an integer string int("42a") # ValueError
copy

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
copy

Questi generano ValueError

1
float("2,5") # ValueError - use a dot, not a comma
copy

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)
copy

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
copy

Errori da evitare

  • int("2.5") genera ValueError - analizzare prima come float(), 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 esempio s == "0".

1. Cosa produce ciascuna riga?

2. Quale chiamata genera un ValueError?

3. Seleziona l'affermazione corretta.

question-icon

Cosa produce ciascuna riga?

int(3.9)
int(" -8 ")

bool("0")

Click or drag`n`drop items and fill in the blanks

question mark

Quale chiamata genera un ValueError?

Select the correct answer

question mark

Seleziona l'affermazione corretta.

Select the correct answer

Tutto è chiaro?

Come possiamo migliorarlo?

Grazie per i tuoi commenti!

Sezione 4. Capitolo 1

Chieda ad AI

expand

Chieda ad AI

ChatGPT

Chieda pure quello che desidera o provi una delle domande suggerite per iniziare la nostra conversazione

bookFondamenti 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) restituisce 2, 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
copy

Questi generano ValueError

12
int("2.5") # ValueError - not an integer string int("42a") # ValueError
copy

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
copy

Questi generano ValueError

1
float("2,5") # ValueError - use a dot, not a comma
copy

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)
copy

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
copy

Errori da evitare

  • int("2.5") genera ValueError - analizzare prima come float(), 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 esempio s == "0".

1. Cosa produce ciascuna riga?

2. Quale chiamata genera un ValueError?

3. Seleziona l'affermazione corretta.

question-icon

Cosa produce ciascuna riga?

int(3.9)
int(" -8 ")

bool("0")

Click or drag`n`drop items and fill in the blanks

question mark

Quale chiamata genera un ValueError?

Select the correct answer

question mark

Seleziona l'affermazione corretta.

Select the correct answer

Tutto è chiaro?

Come possiamo migliorarlo?

Grazie per i tuoi commenti!

Sezione 4. Capitolo 1
some-alt