Python Casting: A Comprehensive Guide
Python casting, also known as type conversion, is the process of converting one data type into another. This is useful when you need to perform operations on data of different types or when you need to store data in a specific format.
Types of Casting
There are two types of casting in Python: implicit casting and explicit casting.
Implicit Casting
Implicit casting occurs when Python automatically converts one data type into another without the need for explicit casting. This is usually done when the operation being performed requires a specific data type.
x = 5 # integer
y = 3.14 # float
result = x + y # implicit casting to float
print(result)
# Output: 8.14
Explicit Casting
Explicit casting occurs when you use built-in functions to convert one data type into another. This is usually done when you need to convert data types explicitly.
x = 5.8 # float
y = int(x) # explicit casting to integer
print(y)
# Output: 5
Built-in Casting Functions
Python provides several built-in functions for casting data types:
int()
: Converts to an integer.float()
: Converts to a float.complex()
: Converts to a complex number.str()
: Converts to a string.list()
: Converts to a list.tuple()
: Converts to a tuple.dict()
: Converts to a dictionary.
x = 5 # integer
y = float(x) # casting to float
z = str(x) # casting to string
print(y) # Output: 5.0
print(z) # Output: '5'