Type Conversion (Casting)

Type Conversion (Casting)

In Python, type conversion, also known as casting, is the process of changing one data type into another. Python provides built-in functions for type conversion, allowing you to work with data in the format you need. In this section, we'll explore the common type conversion functions.

1. Implicit Type Conversion

Python automatically performs some type conversions when necessary. For example, when you perform operations between different data types, Python may convert one of them to match the other:

x = 5
y = 2.0

result = x + y  # 7.0 (x is implicitly converted to float)

This is called implicit type conversion or coercion. Python performs it to ensure that operations involving different data types produce meaningful results.

2. Explicit Type Conversion

You can also perform type conversion explicitly by using built-in functions. The most commonly used functions are:

  • int(): Converts a value to an integer.
  • float(): Converts a value to a floating-point number.
  • str(): Converts a value to a string.
  • bool(): Converts a value to a boolean.

Here are examples of explicit type conversion:

x = "10"
int_x = int(x)  # 10 (string to int)

y = 5
float_y = float(y)  # 5.0 (int to float)

z = 7.8
str_z = str(z)  # "7.8" (float to string)

is_valid = 1
bool_is_valid = bool(is_valid)  # True (int to bool)

3. Combining Strings and Numbers

When working with strings and numbers, you often need to convert numbers to strings for concatenation:

age = 30
message = "I am " + str(age) + " years old."
# "I am 30 years old."

4. Handling Type Conversion Errors

Be cautious when converting data types. Converting a value that cannot be represented in the target type may lead to errors. For example:

value = "Hello, World!"

try:
    integer_value = int(value)
except ValueError as e:
    print("Conversion error:", e)

In this case, trying to convert a string with non-numeric characters to an integer results in a ValueError.

Understanding how to perform type conversion is essential for working with data of different types, such as user input or data processing. Type conversion allows you to transform and manipulate data as needed. In the following sections, we'll explore specific use cases for type conversion in Python.