Notice: This page requires JavaScript to function properly.
Please enable JavaScript in your browser settings or update your browser.
Apprendre Principes Fondamentaux de la Conversion de Types | Interactions Entre Types
Types de Données en Python

bookPrincipes Fondamentaux de la Conversion de Types

La conversion de type permet de passer d’un type de base Python à un autre afin de comparer, calculer ou afficher des valeurs.

Conversion en int

int(x) crée un entier.

  • À partir d’un int : retourne le même nombre ;
  • À partir d’un float : tronque vers zéro (par exemple, int(2.9) retourne 2, int(-2.9) retourne -2) ;
  • À partir d’une chaîne : la chaîne doit représenter un entier (espaces optionnels et signe acceptés).

Conversions valides

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

Ceux-ci lèvent une ValueError

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

Conversion en float

float(x) crée un nombre à virgule flottante.

  • Fonctionne pour les entiers et les chaînes en notation décimale ou scientifique ;
  • Les virgules ne sont pas des séparateurs décimaux en Python.

Conversions valides

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

Ceux-ci génèrent une ValueError

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

Conversion en str

str(x) crée une représentation sous forme de chaîne lisible par l’humain. Privilégier les f-strings lors de la construction de messages.

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

Conversion en bool

bool(x) suit les règles de véracité (truthiness) de Python.

  • Nombres : 0 est False, tout autre nombre est True ;
  • Chaînes : "" (vide) est False, toute chaîne non vide est True (même "0" et "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

Erreurs à éviter

  • int("2.5") génère une ValueError – analyser d’abord avec float(), puis tronquer ou arrondir ;
  • Habitude locale : "2,5" est invalide – utiliser "2.5" ;
  • Traits de soulignement dans les chaînes d’entrée : "1_000" est invalide – supprimer d’abord les traits de soulignement : "1_000".replace("_", "") ;
  • Surprise sur la véracité : bool("0") donne True – comparer explicitement le contenu de la chaîne si nécessaire, par exemple s == "0".

1. Que produit chaque ligne ?

2. Quel appel génère une ValueError ?

3. Choisissez l’énoncé correct.

question-icon

Que produit chaque ligne ?

int(3.9)
int(" -8 ")

bool("0")

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

question mark

Quel appel génère une ValueError ?

Select the correct answer

question mark

Choisissez l’énoncé correct.

Select the correct answer

Tout était clair ?

Comment pouvons-nous l'améliorer ?

Merci pour vos commentaires !

Section 4. Chapitre 1

Demandez à l'IA

expand

Demandez à l'IA

ChatGPT

Posez n'importe quelle question ou essayez l'une des questions suggérées pour commencer notre discussion

Awesome!

Completion rate improved to 3.45

bookPrincipes Fondamentaux de la Conversion de Types

Glissez pour afficher le menu

La conversion de type permet de passer d’un type de base Python à un autre afin de comparer, calculer ou afficher des valeurs.

Conversion en int

int(x) crée un entier.

  • À partir d’un int : retourne le même nombre ;
  • À partir d’un float : tronque vers zéro (par exemple, int(2.9) retourne 2, int(-2.9) retourne -2) ;
  • À partir d’une chaîne : la chaîne doit représenter un entier (espaces optionnels et signe acceptés).

Conversions valides

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

Ceux-ci lèvent une ValueError

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

Conversion en float

float(x) crée un nombre à virgule flottante.

  • Fonctionne pour les entiers et les chaînes en notation décimale ou scientifique ;
  • Les virgules ne sont pas des séparateurs décimaux en Python.

Conversions valides

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

Ceux-ci génèrent une ValueError

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

Conversion en str

str(x) crée une représentation sous forme de chaîne lisible par l’humain. Privilégier les f-strings lors de la construction de messages.

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

Conversion en bool

bool(x) suit les règles de véracité (truthiness) de Python.

  • Nombres : 0 est False, tout autre nombre est True ;
  • Chaînes : "" (vide) est False, toute chaîne non vide est True (même "0" et "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

Erreurs à éviter

  • int("2.5") génère une ValueError – analyser d’abord avec float(), puis tronquer ou arrondir ;
  • Habitude locale : "2,5" est invalide – utiliser "2.5" ;
  • Traits de soulignement dans les chaînes d’entrée : "1_000" est invalide – supprimer d’abord les traits de soulignement : "1_000".replace("_", "") ;
  • Surprise sur la véracité : bool("0") donne True – comparer explicitement le contenu de la chaîne si nécessaire, par exemple s == "0".

1. Que produit chaque ligne ?

2. Quel appel génère une ValueError ?

3. Choisissez l’énoncé correct.

question-icon

Que produit chaque ligne ?

int(3.9)
int(" -8 ")

bool("0")

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

question mark

Quel appel génère une ValueError ?

Select the correct answer

question mark

Choisissez l’énoncé correct.

Select the correct answer

Tout était clair ?

Comment pouvons-nous l'améliorer ?

Merci pour vos commentaires !

Section 4. Chapitre 1
some-alt