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