Python Type Conversion and Type Casting with Examples

Spread the love

Python casting :

The process of converting from one datatype to another is called type casting. In python, First we need to know what are the current datatypes and how we can do it.

We have 2 types of type casting

  1. Implicit type conversion
  2. Explicit type conversion

Implicit type conversion : This type of conversion of automatically happen by the python interpreter.  This process doesn’t require any user actions.  we will use type function to know the datatype of variable.

Example 1:

int_number = 1
float_number = 1.542

addition = int_number + float_number

print("addition number", addition)


print("final variable datatype", type(addition))

print("data type of integer variable after addition with float ", type(int_number))

Output:

addition number 2.542
final variable datatype <class 'float'>
data type of integer variable after addition with float <class 'int'>

By Understanding above output, If we do adding with integer number and float number , The Output is float number.  The datatype conversion is automatically happen.

Note :

If we are planning addition with sting to integer or float we will get error

Example 2:

int_number = 154
sting_number = "154"

addition = int_number + sting_number

print("addition number", addition)


print("final variable datatype", type(addition))

Output:

TypeError: unsupported operand type(s) for +: 'int' and 'str'

Explicit Type Conversion: 

In this conversion, we will convert datatypes to explicitly by using datatype function like int(), float() etc.

In example 2 we are facing the error, we will solve by using explicit type conversion

int_number = 154
sting_number = int("154")

addition = int_number + sting_number

print("addition number", addition)


print("final variable datatype", type(addition))

print("data type of string variable after addition with integer ", type(sting_number))

Output:

addition number 308
final variable datatype <class ‘int’>
data type of string variable after addition with integer <class ‘int’>

Float Conversion:

float_number = 154.5
sting_number = float("154")

addition = float_number + sting_number

print("addition number", addition)


print("final variable datatype", type(addition))

print("data type of string variable after addition with float number", type(sting_number))

Output:

addition number 308.5
final variable datatype <class ‘float’>
data type of string variable after addition with integer <class ‘float’>

admin

admin

Leave a Reply

Your email address will not be published. Required fields are marked *