Curriculum
In this tutorial, you will learn about type conversion in python and its use cases with examples.
Type conversion is the process of converting data one form of data type to another. It is important in performing critical operations. For example, if you are comparing a string to an integer, the integer should be converted into a string first. In this way, the process is more efficient and highly accurate.
Note: You can use the type() function to identify the type of data type used in the statements
Python supports two types of Type Conversions:
The Python interpreter automatically converts one data type to another in implicit type conversion, which means there is no user involvement in implicit type conversion. This type of conversion is commonly used between data types like int and float.
Example
Input:
a= int(input("Enter the value of a:")) b=float(input("Enter the value of b:")) print(type (a)) print(type(b)) c=(a+b) print("Value of c by implicit conversion:", c) print (type (c))
Out1put:
Enter the value of a:23 Enter the value of b:32.89 <class 'int'> <class 'float'> Value of c by implicit conversion: 55.89 <class 'float'>
Here, the given data type is changed by the user based upon the requirement of the problem.
Example:
a= int(input("Enter the value of a:")) b=str(input("Enter the value of b:")) print(type (a)) print(type (b)) b=int(b) #explicit_type_converion c=(a+b) print("Value of c by implicit conversion", c) print (type (c))
Output
Enter the value of a:57 Enter the value of b:75 <class 'int'> <class 'str'> Value of c by implicit conversion 132 <class 'int'>
Let’s look at some common explicit type conversions
The int() function is used to convert the given type to an integer. ‘Base’ specifies the base in which string is if the data type is a string.
The float() is used to convert the given data type to a floating-point number
The str() is used to convert an integer into a string.
The complex()is used to convert real numbers to complex(real,imag) numbers.
the bool() is used to convert the given data type to Boolean and we can perform the Boolean operation.