Search⌘ K
AI Features

Type Conversion and Casting

Explore how Python handles type conversion with implicit coercion and explicit casting. Understand how to use str, int, float, and bool functions to safely convert data, avoid type errors, and manage truthy and falsy values. This lesson equips you to bridge data type boundaries for accurate computation and output formatting.

Python is strict about data types. It will not allow us to add a string of text to a number, nor will it intuitively know how to treat the word "True" as a boolean logic value. To make different types of data work together, we must explicitly convert or "cast" them into compatible forms. Mastering this allows us to bridge the gap between user input (which often arrives as text) and the logic we need to perform (which usually requires numbers or booleans).

Implicit conversion (coercion)

In certain obvious situations, Python handles the conversion for us. This is called implicit conversion or coercion. The most common scenario involves integers and floats. If we perform arithmetic mixing an integer (whole number) and a float (decimal), Python automatically promotes the integer to a float to prevent data loss.

We do not need to write extra code for this; Python ensures the result preserves the decimal precision.

Python 3.14.0
# Mixing integers and floats
integer_score = 50
bonus_multiplier = 1.5
# Python promotes integer_score to a float for the calculation
total_score = integer_score * bonus_multiplier
print(total_score)
print(type(total_score))
  • Line 2: We define integer_score as an int.

  • Line 3: We define bonus_multiplier as a float.

  • Line 6: When multiplying, Python temporarily treats 50 as 50.0. The result, 75.0, is stored as a float.

  • Lines 8–9: We verify that the final result is indeed a float.

Explicit conversion (casting)

When the conversion is not obvious, like adding text to a ...