Python Type Conversion

๐Ÿ”น What is Type Conversion?

Type conversion is the process of changing the data type of a variable.
Python provides two types of type conversion:

  • Implicit Conversion โ€“ Automatically handled by Python.
  • Explicit Conversion โ€“ Manually done using functions like int(), float(), str(), etc.

1. Implicit Type Conversion (Automatic)

Python automatically converts a variable to the appropriate type when needed.

num_int = 10   # Integer
num_float = 5.5   # Float

result = num_int + num_float  # Python converts int to float automatically
print(result)   # Output: 15.5
print(type(result))  # Output: <class 'float'>

Try It Now

2. Explicit Type Conversion (Type Casting)

Explicit conversion (casting) is done using built-in functions:

Function Converts To
int(x) Integer
float(x) Float
str(x) String
list(x) List
tuple(x) Tuple
set(x) Set
dict(x) Dictionary
bool(x) Boolean

ย 3. Examples of Explicit Type Conversion

3.1 Integer to Float & String

num = 10
print(float(num))  # Output: 10.0
print(str(num))  # Output: "10"

Try It Now

3.2 String to Integer & Float

text = "123"
print(int(text))  # Output: 123
print(float(text))  # Output: 123.0

Try It Now

3.3 List to Tuple & Set

my_list = [1, 2, 3, 3]
print(tuple(my_list))  # Output: (1, 2, 3, 3)
print(set(my_list))  # Output: {1, 2, 3}  (removes duplicates)

Try It Now

3.4 Boolean to Integer

print(int(True))  # Output: 1
print(int(False))  # Output: 0

Try It Now

ย 4. Handling Errors in Type Conversion

If you try converting incompatible data types, Python throws an error.

print(int("hello"))  # โŒ ValueError: invalid literal for int()

Try It Now

โœ… Solution:

text = "123"
if text.isdigit():
    print(int(text))  # โœ… Safe conversion
else:
    print("Not a valid number")

Try It Now

Best Practices for Type Conversion

  • โœ… Use isinstance() to check type before conversion
x = "100"
if isinstance(x, str):
    x = int(x)
print(x)  # Output: 100

Try It Now

  • โœ… Avoid unnecessary conversions
# โŒ Inefficient
x = int(str(10))

# โœ… Efficient
x = 10

Try It Now

  • โœ… Handle conversion errors using try-except
try:
    num = int("abc")  # โŒ This will cause an error
except ValueError:
    print("Invalid conversion!")

Try It Now