The process of converting a one data type into another data type is known as type conversion. There are mainly two types of type conversion methods available in Python, which includes following-
Implicit Type Conversion:- When Python data type conversion takes place during the compilation or the run time, then it’s known as implicit data type conversion. We don’t have to explicitly convert the data type into another data type, as Python handles the implicit data type conversion.
x = 5
y = 2.5
sum = x + y
print(type(sum)) # float
In the above example, we have taken two variables (i.e. x and y) of integer and float data types and added them together and stored in third variable (i.e. sum). When we checked the data type of the third variable, we can see that the data type of the third variable variable has been automatically converted into the float data type by the Python compiler.
Explicit Type Conversion:- It is also known as type casting. It takes place when the programmer clearly and explicitly defines the data type conversion in the program. For this, there are some in-built Python functions available, which are given below-
Function | Description |
---|---|
int(x [base]) | It converts x to an integer, and base specifies the number base. |
float(x) | It converts x to a floating point number. |
complex(real [imag]) | It creates a complex number. |
str(x) | It converts x to a string. |
tuple(x) | It converts x to a tuple. |
list(x) | It converts x to a list. |
set(x) | It converts x to a set. |
dict(x) | It creates a dictionary and here x should be a sequence of (key, value) tuples. |
ord(x) | It converts a single character to its integer value. |
hex(x) | It converts an integer to a hexadecimal string. |
oct(x) | It converts an integer to an octal string. |
x = float(5)
y = int(2.5)
z = int("7")
# Type
print(type(x)) # float
print(type(y)) # int
print(type(z)) # int
# Output
print(x) # 5.0
print(y) # 2
print(z) # 7