Explicit Type Conversion in Python (Type Casting)
Definition:
Explicit type conversion occurs when the programmer manually converts one data type to another
using Python's built-in functions.
Examples:
1. Using `int()`
- Converts a number or a string to an integer (if possible).
- Non-numeric characters in strings cause errors.
# Float to Integer
num_float = 7.9
result = int(num_float) # Converts to Integer
print(result) # Output: 7
print(type(result)) # Output: <class 'int'>
# String to Integer
str_num = "10"
result = int(str_num) # Converts to Integer
print(result) # Output: 10
print(type(result)) # Output: <class 'int'>
2. Using `float()`
- Converts an integer or a string to a float.
# Integer to Float
num_int = 5
result = float(num_int) # Converts to Float
print(result) # Output: 5.0
print(type(result)) # Output: <class 'float'>
# String to Float
str_num = "3.14"
result = float(str_num) # Converts to Float
print(result) # Output: 3.14
print(type(result)) # Output: <class 'float'>
3. Using `complex()`
- Converts numbers or strings to a complex number.
# Integer to Complex
num_int = 4
result = complex(num_int) # Converts to Complex
print(result) # Output: (4+0j)
print(type(result)) # Output: <class 'complex'>
# Float to Complex
num_float = 2.5
result = complex(num_float) # Converts to Complex
print(result) # Output: (2.5+0j)
# Two arguments for Complex (real, imaginary)
real = 3
imag = 4
result = complex(real, imag) # Creates a Complex number
print(result) # Output: (3+4j)
Key Points:
- Explicit conversions must be used carefully to avoid runtime errors.
- Examples of errors:
python
str_num = "abc"
print(int(str_num)) # Raises ValueError: invalid literal for int()