Type conversion and casting in python programming

12/20/2021

Type conversion and casting in python

Go Back

Type conversion and casting in python programming

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: 

  1. Implicit type conversion
  2. Explicit type conversion. 
Type conversion and casting in python

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.

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))

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.

 Below is example  explicit type conversion... Here we describe how add  string and integer using explicit 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))

 

Conclusion

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

Table of content