Type conversion and casting in python programming
Type conversion and casting in python
Before learning Type Conversion in Python, you should have knowledge about Python Data Types.
A Python data type conversion method is called a conversion of type.
Python generally provides two types of conversion methods:
In Implicit type conversion, Python automatically converts one data type to another data type. This process doesn't need any user involvement.
Below is example of implicit type conversion.
Describe conversion of integer to float...
num_int = 123
num_flo = 1.23
num_new = num_int + num_flo
print("datatype of num_int:",type(num_int))
print("datatype of num_flo:",type(num_flo))
print("Value of num_new:",num_new)
print("datatype of num_new:",type(num_new))
In Explicit Type Conversion, users convert the data type of an object to required data type. We use the predefined functions like int()
, float()
, str()
, etc to perform explicit type conversion.
num_int = 123
num_str = "456"
print("Data type of num_int:",type(num_int))
print("Data type of num_str before Type Casting:",type(num_str))
num_str = int(num_str)p
rint("Data type of num_str after Type Casting:",type(num_str))
num_sum = num_int + num_str
print("Sum of num_int and num_str:",num_sum)
print("Data type of the sum:",type(num_sum))
Type Conversion is the conversion of an object from one data type to another data type. Implicit Type Conversion is automatically performed by the Python interpreter.type conversion is the process of converting data from one type to another