๐น 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'>
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"
3.2 String to Integer & Float
text = "123" print(int(text)) # Output: 123 print(float(text)) # Output: 123.0
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)
3.4 Boolean to Integer
print(int(True)) # Output: 1 print(int(False)) # Output: 0
ย 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()
โ Solution:
text = "123" if text.isdigit(): print(int(text)) # โ Safe conversion else: print("Not a valid number")
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
- โ Avoid unnecessary conversions
# โ Inefficient x = int(str(10)) # โ Efficient x = 10
- โ
Handle conversion errors using
try-except
try: num = int("abc") # โ This will cause an error except ValueError: print("Invalid conversion!")