2.6 Type Casting
Learning the process of changing the data type of a value from one type to another, using the built-in functions int(), float(), str(), and bool().
Type casting (or type conversion) is the process of explicitly changing the data type of a value. Python, as a dynamically typed language, handles many conversions automatically (implicit conversion), but there are cases where we need to do it explicitly (explicit conversion). This is done using functions that have the same name as the type we want to convert to, such as `int()`, `float()`, `str()`, and `bool()`.
Conversion Examples
# Convert to integer (int)
string_num = "123"
float_num = 45.67
bool_true = True
int_from_string = int(string_num)
int_from_float = int(float_num) # Important: Truncates the decimal part, does not round.
int_from_bool = int(bool_true) # True becomes 1, False becomes 0
print(f"'{string_num}' (str) as int: {int_from_string}")
print(f"{float_num} (float) as int: {int_from_float}")
print(f"{bool_true} (bool) as int: {int_from_bool}")
print("-" * 20)
# Convert to float
int_num_float = 45
float_from_int = float(int_num_float)
print(f"{int_num_float} (int) as float: {float_from_int}")
print("-" * 20)
# Convert to string (str)
num_to_str = 123
list_to_str = [1, 2, 3]
str_from_num = str(num_to_str)
str_from_list = str(list_to_str)
print(f"{num_to_str} (int) as str: '{str_from_num}'")
print(f"{list_to_str} (list) as str: '{str_from_list}'")
print("-" * 20)
# Convert to Boolean (bool)
# Rule: Anything "empty" or zero becomes False. Everything else becomes True.
print(f"bool(0): {bool(0)}")
print(f"bool(1): {bool(1)}")
print(f"bool(-10): {bool(-10)}")
print(f"bool(''): {bool('')} (empty string)")
print(f"bool('Hello'): {bool('Hello')}")
print(f"bool([]): {bool([])} (empty list)")
print(f"bool([1, 2]): {bool([1, 2])}")
Tip!
Attempting to convert an incompatible value will raise an error. For example, executing `int("abc")` will lead to a `ValueError` because the string "abc" cannot be interpreted as a number. We will learn how to handle such errors safely in Chapter 7.
Practical Exercises
Explore More with AI
Use AI to generate new examples, delve deeper into theory, or get your questions answered.