![]() |
VOOZH | about |
Type Casting is the method to convert the Python variable datatype into a certain data type in order to perform the required operation by users. We will see various techniques for typecasting. There can be two types of Type Casting in Python:
Implicit type conversion occurs when Python automatically converts one data type to another during an operation to ensure correct and safe evaluation, without requiring any action from the user.
<class 'int'> <class 'float'> 10.0 <class 'float'> 21.0 <class 'float'>
Explicit type conversion is when the programmer manually changes a value’s data type using built-in type casting functions, usually when automatic conversion is not possible or a specific type is needed.
Commonly used type casting functions in Python are:
Converting Int to Float in with the float() function.
5.0 <class 'float'>
Converting Float to int datatype in Python with int() function.
5 <class 'int'>
Converting int to String datatype in Python with str() function.
5 <class 'str'>
Casting string data type into float data type with float() function.
5.9 <class 'float'>
Converting string to int datatype in Python with int() function. If the given string is not number, then it will throw an error.
Output
5
<class 'int'>
---------------------------------------------------------------------------
ValueError Traceback (most recent call last)
/tmp/ipython-input-1957009883.py in <cell line: 0>()
9 print(type(n))
10
---> 11 print(int(b))
12 print(type(b))
ValueError: invalid literal for int() with base 10: 't'
The string "5" is successfully converted into an integer 5. Since 't' is not a number, Python cannot convert it into an integer.
If we try to directly add an integer and a string, Python will throw an error because they are different data types.
Output
TypeError: unsupported operand type(s) for +: 'int' and 'str'
We should first convert the string into an integer and then add: