Type Casting

The process of converting the value of one data type (integer, string, float, etc.) to another data type is called type conversion. Python has two types of type conversion.

  1. Implicit Type Conversion
  2. Explicit Type Conversion

Implicit Type Conversion

In Implicit type conversion, Python automatically converts one data type to another data type. This process doesn't need any user involvement.

Python promotes the conversion of the lower data type (integer) to the higher data type (float) to avoid data loss.

Converting integer to float

 

 

Addition of string(higher) data type and integer(lower) datatype


 

In the above program,

  • We add two variables num_int and num_str.
  • As we can see from the output, we got TypeError. Python is not able to use Implicit Conversion in such conditions.
  • However, Python has a solution for these types of situations which is known as Explicit Conversion.

 

Explicit Type Conversion

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.

This type of conversion is also called typecasting because the user casts (changes) the data type of the objects.

Syntax :

<required_datatype>(expression)

 

Addition of string and integer using explicit conversion

 

 

 

 

 

 

 

No comments:

Post a Comment