In Python, typecasting and type conversion allow developers to change the data type of a variable. This is useful when you need to perform operations that require specific types or to ensure compatibility between different types. Python supports both explicit typecasting (done manually) and implicit type conversion (done automatically by Python).
Explicit typecasting is performed manually using Python's built-in type conversion functions. Commonly used functions include:
int()
: Converts a value to an integerfloat()
: Converts a value to a floating-point numberstr()
: Converts a value to a stringbool()
: Converts a value to a boolean
# String to integer conversion
num_str = "25"
num_int = int(num_str)
print("String:", num_str, "Type:", type(num_str))
print("Integer:", num_int, "Type:", type(num_int))
Output:
String: 25 Type:Integer: 25 Type:
# Integer to float conversion
num = 10
num_float = float(num)
print("Integer:", num, "Type:", type(num))
print("Float:", num_float, "Type:", type(num_float))
Output:
Integer: 10 Type:Float: 10.0 Type:
# Number to string conversion
value = 42
value_str = str(value)
print("Value:", value, "Type:", type(value))
print("String:", value_str, "Type:", type(value_str))
Output:
Value: 42 Type:String: 42 Type:
# Boolean conversion
print(bool(0)) # False
print(bool(1)) # True
print(bool("")) # False
print(bool("Python")) # True
Output:
False True False True
Implicit type conversion, also known as type coercion, is performed automatically by Python when it makes sense. Python automatically converts one data type to another in certain operations.
# Implicit conversion
num1 = 10 # Integer
num2 = 2.5 # Float
result = num1 + num2
print("Result:", result, "Type:", type(result))
Output:
Result: 12.5 Type:
# Implicit boolean to integer conversion
is_valid = True
num = 5
result = is_valid + num
print("Result:", result, "Type:", type(result))
Output:
Result: 6 Type:
User inputs are always captured as strings. They often need to be converted to numbers for calculations.
# User input conversion
age = int(input("Enter your age: "))
print("Next year, you will be", age + 1, "years old.")
# Mixed type operations
a = 10 # Integer
b = 3.5 # Float
result = a * b
print("Result:", result, "Type:", type(result))
If you attempt to convert an invalid value, Python will raise an error. Use try-except
to handle such cases.
# Handling conversion errors
try:
num = int("abc")
print(num)
except ValueError:
print("Error: Cannot convert to integer.")
Output:
Error: Cannot convert to integer.
Typecasting and type conversion are essential concepts in Python that allow flexibility in handling different data types. While implicit conversion simplifies operations, explicit typecasting gives precise control over type changes. Mastering these techniques helps in writing robust and error-free Python programs.