Type Casting means converting one type into another data type in order to the operation required to be performed inside an expression. In this article, we will see the various techniques for typecasting.
Also Read: Data Types in Python
There can be two types of Type Casting in Python –
- Implicit Type Casting
- Explicit Type Casting
Implicit Type Conversion:
In this method python interpreter takes the responsibility to convert one data type to another type implicitly and not done by any programmer or user called implicit Type Conversion.
# Python program to demonstrate # implicit type Casting # Python automatically converts # a to int a = 7 print(type(a)) # Python automatically converts # b to float b = 3.0 print(type(b)) # Python automatically converts # c to int as it is a floor addition c = a + b print(c) print(type(c)) # Python automatically converts # c to int as it is a floor multiplication d = a * b print(d) print(type(d))
Output:
<class 'int'>
<class 'float'>
10.0
<class 'float'>
21.0
<class 'float'>
Explicit Type Casting:
In this method, python expression needs user or programmer involvement to convert the variable or constant data type into a certain data type in order to operation required.
Mainly in python the type casting can be done with help of these data type function:
- Int() : Int() function take float or string as an argument and return int type object.
- float() : float() function take int or string as an argument and return float type object.
- str() : str() function take float or int as an argument and return string type object.
Let’s see some example of type casting:
Type Casting int to float:
Here, we are casting integer object to float object with float() function.
# Python program to demonstrate # type Casting # int variable a = 5 # typecast to float n = float(a) print(n) print(type(n))
Output:
5.0
<class 'float'>
Type Casting float to int:
Here, we are casting float data type into integer data type with int() function.
# Python program to demonstrate # type Casting # int variable a = 5.9 # typecast to int n = int(a) print(n) print(type(n))
Output:
5
<class 'int'>
Type Casting int to string:
# Python program to demonstrate # type Casting # int variable a = 5 # typecast to str n = str(a) print(n) print(type(n))
Output:
5
<class 'str'>
Type Casting string to int:
Here, we are casting string data type into integer data type with int() function.
# Python program to demonstrate # type Casting # string variable a = "5" # typecast to int n = int(a) print(n) print(type(n))
Output:
5
<class 'int'>
Type Casting String to float:
Here, we are casting string data type into float data type with float() function.
# Python program to demonstrate # type Casting # string variable a = "5.9" # typecast to float n = float(a) print(n) print(type(n))
Output:
5.9
<class 'float'>
Please comment and share this post if you find helpful content and WhatsApp us to update this post.