Hey guys! Welcome to an another interesting article on Python Programming Language.
Here, we will discuss about the Type conversion of Python programming language.
So, let's dive in!
Type Conversion In Python
Type Conversion function of Python is defined in order to convert one data type into another data type which is very usefull in competitive and day to day programming.
Kinds of Type Conversion in Python
Now, we will learn about the kinds of Type Conversion in Python. There are two types of Type Conversion in Python which are discussed as follows;
A. Implicit Type Conversion
Implicit Type Conversion is a type of Type Conversion in Python where the Python interpreter converts the one data type into another data type automatically without any involvement of the user.
Example:
x = 198
y= 1.50
z = x + y
print("datatype of x:",type(x))
print("datatype of y:",type(y))
print("Value of z:",z)
print("datatype of z:",type(z))
Output
datatype of x: <class 'int'>
datatype of y: <class 'float'>
Value of z: 199.5
datatype of z: <class 'float'>
B. Explicit Type Conversion
Explicit Type Conversion is a type of Type Conversion in Python where the user changes the one data type into another data type manually according to their requirements.
Example:
x = 100
y = "786"
print("Data type of x:",type(x))
print("Data type of y before Type Casting:",type(y))
y = int(y)
print("Data type of num_str after Type Casting:",type(y))
z = x + y
print("Sum of x and y:",z)
print("Data type of the sum:",type(z))
Output
Data type of x: <class 'int'>
Data type of y before Type Casting: <class 'str'>
Data type of num_str after Type Casting: <class 'int'>
Sum of x and y: 886
Data type of the sum: <class 'int'>
There are 12 different forms of Explicit Type Conversion which are explained as follows;
1. int(a,base): This function is used to convert any data type into integer.
2. float(): This function converts any data type into a floating point number.
3. ord(): It converts a character into integer.
4. hex(): This functions converts integer into hexadecimal string.
5. oct(): This function converts integer into octal string.
6. tuple(): It converts into a tuple.
7. set(): It is used to return the type after the conversion into set.
8. list(): This function converts any data type into a list type.
9. dict(): It converts a tuple of order (key,value) to a dictionary.
10. str(): This function converts integer to a string.
11. complex(real,imag): It is used to convert real numbers into complex(real,imag) number.
12. chr(number): It is used to convert number into its corresponding ASCII character.
Conclusion
Above we have discussed the Type conversion of Python programming language. Type Conversion function of python is defined in order to convert one data type into another data type which is very usefull in competitive and day to day programming. There are two types of Type Conversion in Python i.e. Implicit and Explicit Type Conversion. I hope this information is helpful to you all.