2.3 Type Conversion
Type conversion is the process of converting one data type into another. In Python, this can be done both implicitly (automatically) or explicitly (manually). This is useful when you need to convert data types to perform certain operations or format data in a specific way. Understanding how to work with type conversion is essential for preventing errors and ensuring your code runs smoothly.
In this section, we will explore:
- Implicit type conversion
- Explicit type conversion
- Common type conversion functions
2.3.1 Implicit Type Conversion
Implicit type conversion, also known as coercion, happens automatically when Python converts one data type to another during an operation, without requiring explicit instructions from the developer.
Python usually performs implicit type conversion when you are working with mixed data types in an expression, such as adding an integer to a float. In these cases, Python converts the integer to a float to avoid losing precision.
Examples of Implicit Type Conversion
Example 1: Integer to Float Conversion
x = 5 # Integer
y = 2.0 # Float
# Implicit conversion of x (int) to a float
result = x + y
print(result) # Output: 7.0
print(type(result)) # Output: <class 'float'>
In this example, Python automatically converts the integer x
to a float so that it can add it to y
, which is already a float.
Example 2: Boolean to Integer Conversion
x = True
y = 5
# Implicit conversion of True (boolean) to 1 (integer)
result = x + y
print(result) # Output: 6
print(type(result)) # Output: <class 'int'>
In this case, Python converts the boolean True
to the integer 1
during the addition.
Limitations of Implicit Type Conversion
Python does not perform implicit conversions between all types. For example, trying to add a string and an integer will raise an error:
x = "100"
y = 5
result = x + y # Raises TypeError
Python raises a TypeError
because it cannot implicitly convert a string to an integer for addition.
2.3.2 Explicit Type Conversion
Explicit type conversion (also known as type casting) is when you manually convert a value from one data type to another using Python's built-in functions. This gives you full control over how and when types are converted.
Common type conversion functions:
int()
– Converts a value to an integerfloat()
– Converts a value to a floatstr()
– Converts a value to a stringbool()
– Converts a value to a boolean
Examples of Explicit Type Conversion
Example 1: Converting Strings to Integers
num_str = "100"
num_int = int(num_str) # Convert string to integer
print(num_int) # Output: 100
print(type(num_int)) # Output: <class 'int'>
Example 2: Converting Integers to Strings
age = 25
age_str = str(age) # Convert integer to string
print(age_str) # Output: "25"
print(type(age_str)) # Output: <class 'str'>
Example 3: Converting Floats to Integers
pi = 3.14159
pi_int = int(pi) # Convert float to integer (truncates the decimal part)
print(pi_int) # Output: 3
Example 4: Converting Integers to Floats
x = 10
x_float = float(x) # Convert integer to float
print(x_float) # Output: 10.0
Precision in Explicit Conversion
When converting from a float to an integer, Python truncates (removes) the decimal part instead of rounding it. For example:
x = 9.99
y = int(x)
print(y) # Output: 9 (not rounded to 10)
If rounding is required, use the round()
function:
x = 9.99
y = round(x)
print(y) # Output: 10
2.3.3 Common Type Conversion Functions
Python provides several built-in functions to explicitly convert data types. Let’s go over these functions in more detail:
2.3.3.1 int()
The int()
function converts a value to an integer. This works with strings, floats, and booleans. When converting a float, the function truncates the decimal part.
Examples:
# String to Integer
num_str = "42"
num_int = int(num_str) # Output: 42
# Float to Integer
num_float = 3.9
num_int = int(num_float) # Output: 3
# Boolean to Integer
val_true = int(True) # Output: 1
val_false = int(False) # Output: 0
2.3.3.2 float()
The float()
function converts a value to a floating-point number. This works with strings, integers, and booleans.
Examples:
# Integer to Float
num_int = 10
num_float = float(num_int) # Output: 10.0
# String to Float
num_str = "3.14"
num_float = float(num_str) # Output: 3.14
# Boolean to Float
val_true = float(True) # Output: 1.0
val_false = float(False) # Output: 0.0
2.3.3.3 str()
The str()
function converts a value to a string. This works with any data type, including integers, floats, and booleans.
Examples:
# Integer to String
x = 100
x_str = str(x) # Output: "100"
# Float to String
pi = 3.14159
pi_str = str(pi) # Output: "3.14159"
# Boolean to String
val = True
val_str = str(val) # Output: "True"
2.3.3.4 bool()
The bool()
function converts a value to a boolean. Python treats zero, empty sequences (like empty strings, lists, or tuples), and None as False
, while all other values are treated as True
.
Examples:
# Integer to Boolean
x = 0
y = 42
print(bool(x)) # Output: False (0 is False)
print(bool(y)) # Output: True (non-zero is True)
# String to Boolean
print(bool("")) # Output: False (empty string)
print(bool("Hello")) # Output: True (non-empty string)
2.3.4 Converting Between Complex Data Types
You can also convert between more complex data types, such as lists, tuples, and sets. These conversions are particularly useful when you need to transform data structures for specific operations.
2.3.4.1 List to Tuple
my_list = [1, 2, 3]
my_tuple = tuple(my_list)
print(my_tuple) # Output: (1, 2, 3)
2.3.4.2 Tuple to List
my_tuple = (1, 2, 3)
my_list = list(my_tuple)
print(my_list) # Output: [1, 2, 3]
2.3.4.3 List to Set
my_list = [1, 2, 2, 3]
my_set = set(my_list)
print(my_set) # Output: {1, 2, 3} (duplicates are removed in sets)
2.3.5 Handling Conversion Errors
Not all values can be converted between types. When attempting to convert an incompatible value, Python raises a ValueError
.
Example:
# Attempting to convert a non-numeric string to an integer
x = "abc"
y = int(x) # Raises ValueError: invalid literal for int() with base 10
To avoid such errors, you should ensure the value is compatible before attempting conversion, or use exception handling to catch errors.
Example:
num_str = "abc"
try:
num_int = int(num_str)
except ValueError:
print("Invalid conversion")
2.3.6 Summary
- Implicit type conversion occurs automatically during operations where necessary, but it is limited to compatible types (e.g., integers to floats).
- Explicit type conversion is done manually using functions like
int()
,float()
,str()
, andbool()
. - Python provides a variety of type conversion functions to change one data type to another, such as converting strings to numbers or numbers to strings.
- Be mindful of conversion errors, particularly when working with incompatible types, and handle such cases with proper error checking or exception handling.
Understanding type conversion is essential for working with mixed data types in Python and avoiding common programming pitfalls
. This knowledge will help you when handling user input, manipulating data, and performing mathematical operations across different data types.