What is Casting in Python?
Casting in Python is the process of explicitly converting data types using built-in functions. Python is a dynamically-typed language, meaning that variables can change types automatically during execution. However, casting is used when a specific type is required for operations or compatibility.
Types of Casting in Python
Python supports the following types of casting:
- Implicit Casting
- Explicit Casting
Let’s explore each of these in detail.
1. Implicit Casting
In implicit casting, Python automatically converts a data type into another without requiring user intervention. This typically happens when a lower-precision type is converted into a higher-precision type to avoid data loss.
Example of Implicit Casting:
# Implicit casting from int to float
num_int = 10
num_float = num_int + 5.5
print(num_float) # Output: 15.5
print(type(num_float)) # Output: <class 'float'>
In the above example, Python automatically converts the integer num_int to a float to perform the addition with a float value.
2. Explicit Casting
Explicit casting requires using Python’s built-in functions to convert a variable from one type to another. The main functions used for explicit casting are:
- int(): Converts to an integer.
- float(): Converts to a floating-point number.
- str(): Converts to a string.
- complex(): Converts to a complex number.
- bool(): Converts to a Boolean value.
Using the int() Function
The int() function converts a number or string into an integer. Non-integer values in strings must be removed, or the function will raise an error.
Examples of int() Usage:
# Float to int
num_float = 7.9
num_int = int(num_float)
print(num_int) # Output: 7
# String to int
num_str = "123"
num_int = int(num_str)
print(num_int) # Output: 123
Points to Remember:
- It truncates the decimal part when converting from a float.
- Strings must represent valid integers.
Using the float() Function
The float() function converts an integer or string into a floating-point number.
Examples of float() Usage:
# Int to float
num_int = 10
num_float = float(num_int)
print(num_float) # Output: 10.0
# String to float
num_str = "45.67"
num_float = float(num_str)
print(num_float) # Output: 45.67
Points to Remember:
- Strings must represent valid float values.
Using the str() Function
The str() function converts numbers and other data types into strings. This is useful for concatenating numeric values with strings or preparing data for display.
Examples of str() Usage:
# Int to string
num_int = 100
num_str = str(num_int)
print(num_str) # Output: '100'
print(type(num_str)) # Output: <class 'str'>
# Float to string
num_float = 10.5
num_str = str(num_float)
print(num_str) # Output: '10.5'
Using the complex() Function
The complex() function converts numbers or strings into complex numbers, with the format a + bj.
Examples of complex() Usage:
# Int to complex
num_int = 5
num_complex = complex(num_int)
print(num_complex) # Output: (5+0j)
# Float to complex
num_float = 3.5
num_complex = complex(num_float)
print(num_complex) # Output: (3.5+0j)
Using the bool() Function
The bool() function converts a value into a Boolean (True or False). Any non-zero or non-empty value evaluates to True, while zero or empty values evaluate to False.
Examples of bool() Usage:
# Integer to boolean
num = 10
print(bool(num)) # Output: True
# String to boolean
text = ""
print(bool(text)) # Output: False
Type Conversion for Collections
Python also allows type casting for collections, such as lists, tuples and sets.
Examples:
# List to tuple
list_data = [1, 2, 3]
tuple_data = tuple(list_data)
print(tuple_data) # Output: (1, 2, 3)
# Tuple to list
tuple_data = (4, 5, 6)
list_data = list(tuple_data)
print(list_data) # Output: [4, 5, 6]
Common Errors in Casting
Invalid Format Strings:
num = "abc"
int_num = int(num) # Raises ValueError
Precision Loss:
When converting float to int, the fractional part is lost.
Unsupported Conversions:
Certain conversions like int(‘1.5’) are not supported without additional steps.