What is Type Casting in Python?

Subh Singh
Invent the Future

Type casting means converting one data type to another. This process is called type casting. The data type can be changed either manually by the user or automatically by the Python interpreter.

Therefore, there are two types of type casting:

1. Explicit Type Conversion (Type Casting)

When the user manually converts one data type into another, it is called explicit type conversion. Python provides built-in functions, such as int(), float(), str(), and bool(). They are used to convert one data type into another.

Example:

age_str = "24"      # Now you will change this string data into an integer.

age_int = int(age_str)    # int() changes the string data into an integer.

print(age_int + 5)        # print() adds both integer values and displays the output: 29

2. Implicit Type Conversion (Type Casting)

In this type of conversion, the user does not need to change the data type. The Python interpreter supports implicit type conversion by automatically converting one data type to another.

Example:

a_int = 8        # Integer
b_float = 2.5    # Float

result = a_int + b_float

print(result)    # Output: 10.5

Here,
Python first automatically converts a_int from int to float. Then it adds both variables. Therefore, the output is 10.5.