Last modified: Feb 15, 2025 By Alexander Williams
Casting and Type Conversion in Python
In Python, casting and type conversion are essential concepts. They allow you to change the data type of a variable. This is useful when working with different data types.
Table Of Contents
What is Casting?
Casting is the process of converting a variable from one data type to another. Python provides built-in functions for this purpose. These functions include int()
, float()
, and str()
.
Implicit vs Explicit Conversion
Python supports two types of conversion: implicit and explicit. Implicit conversion happens automatically. Explicit conversion requires manual intervention.
Implicit Conversion
Implicit conversion occurs when Python automatically converts one data type to another. For example, adding an integer and a float results in a float.
# Implicit conversion example
num_int = 10
num_float = 5.5
result = num_int + num_float # Python converts num_int to float
print(result)
Output: 15.5
Explicit Conversion
Explicit conversion is done using Python's built-in functions. You manually convert the data type. This is also known as casting.
# Explicit conversion example
num_str = "123"
num_int = int(num_str) # Convert string to integer
print(num_int)
Output: 123
Common Type Conversion Functions
Python provides several functions for type conversion. These include int()
, float()
, str()
, and bool()
.
Using int()
The int()
function converts a value to an integer. It can convert from float or string. If the string is not a valid number, it raises an error.
# int() function example
num_float = 10.7
num_int = int(num_float) # Convert float to integer
print(num_int)
Output: 10
Using float()
The float()
function converts a value to a float. It can convert from integer or string. If the string is not a valid number, it raises an error.
# float() function example
num_int = 10
num_float = float(num_int) # Convert integer to float
print(num_float)
Output: 10.0
Using str()
The str()
function converts a value to a string. It can convert from integer, float, or boolean. This is useful for concatenating strings.
# str() function example
num_int = 10
num_str = str(num_int) # Convert integer to string
print("The number is: " + num_str)
Output: The number is: 10
Handling Errors in Type Conversion
Type conversion can raise errors if the conversion is not possible. For example, converting a non-numeric string to an integer will raise a ValueError.
# Error handling example
try:
num_str = "abc"
num_int = int(num_str) # This will raise a ValueError
except ValueError:
print("Conversion failed: Invalid literal for int()")
Output: Conversion failed: Invalid literal for int()
Conclusion
Casting and type conversion are vital in Python. They allow you to work with different data types seamlessly. Use int()
, float()
, and str()
for explicit conversion. Always handle errors to avoid crashes.
For more on Python variables, check out our guide on Understanding Python Variable Types. If you're dealing with None
values, read Checking if a Variable is None in Python.