Explain TypeCasting in Python?

Type Casting is the method to convert the variable data type into a certain data type in order to the operation required to be performed by users. In this session, we will see the various technique for typecasting. There can be two types of Type Casting in Python –

  1. Implicit Type Casting: In this, methods, Python converts data type into another data type automatically. In this process, users don’t have to involve in this process.
  2. Explicit Type Casting: In this method, Python need user involvement to convert the variable data type into certain data type in order to the operation required.

Mainly in type casting can be done with 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.

Example: Converting 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))`

When we run the above program, the output will be:

datatype of num_int: <class 'int'>
datatype of num_flo: <class 'float'> 
Value of num_new: 124.23
datatype of num_new: <class 'float'>

In the above program,

  • We add two variables num_int and num_flo, storing the value in num_new.
  • We will look at the data type of all three objects respectively.
  • In the output, we can see the data type of num_int is an integer while the data type of num_flo is a float.
  • Also, we can see the num_new has a float data type because Python always converts smaller data types to larger data types to avoid the loss of data.