The conversion of one data type into the other data type, to perform the required operation, is known as typecasting or type conversion.
There are two types of typecasting in Python:
- Explicit Type Conversion
- Implicit Type Conversion
Explicit Type Conversion
Manually conversion of one data type into another data type, is known as explicit type conversion. This is typically done when you need to perform operations that require a specific data type.
It can be done using Python’s built-in type conversion functions such as:
int()
— converts to integerfloat()
— converts to floatstr()
— converts to stringbool()
— converts to boolean, and so on.
For example:
x = 5
print(type(x)) #output: <class 'int'>
y = str(x) # Explicitly converts integer to string
print(type(y)) #output: <class 'str'>
Implicit Type Conversion
Implicit type conversion, happens automatically by the Python interpreter when it needs to perform operations with different data types.
Python automatically converts the lower data type into a higher data type to avoid data loss and ensure the operation is performed without errors.
For example:
x = 3
print(type(x)) #output: <class 'int'>
y = 7.1
print(type(y)) #output: <class 'float'>
z = x + y
print(z)
print(type(z)) #output: <class 'float'>
# Python automatically converts z to float as it is a float addition
In this example, the integer x
is automatically converted to a float before the addition operation, resulting in a float.