Casting in Python

Casting in Python refers to converting a variable from one data type to another. This is a common operation when you need to perform different operations on data types or ensure compatibility with functions that require specific types.

Casting to Integer

You can cast other types to integers using the int() function. This is useful when you have numeric values in string format or floating-point numbers that need to be converted to integers.

Python
# Casting a string to an integer
num_str = "123"
num_int = int(num_str)
print(num_int)  # Output: 123

# Casting a float to an integer
num_float = 12.99
num_int = int(num_float)
print(num_int)  # Output: 12

Casting to Float

To convert other data types to floats, use the float() function. This is useful for performing arithmetic operations that require decimal precision.

Python
# Casting a string to a float
num_str = "123.45"
num_float = float(num_str)
print(num_float)  # Output: 123.45

# Casting an integer to a float
num_int = 123
num_float = float(num_int)
print(num_float)  # Output: 123.0

Casting to String

You can convert other types to strings using the str() function. This is particularly useful when you need to concatenate numbers with strings or print variables in a readable format.

Python
# Casting an integer to a string
num_int = 123
num_str = str(num_int)
print(num_str)  # Output: "123"

# Casting a float to a string
num_float = 12.34
num_str = str(num_float)
print(num_str)  # Output: "12.34"

Casting to Boolean

The bool() function converts values to Boolean (True or False). This is helpful for condition checks and logical operations.

Python
# Casting various types to boolean
print(bool(0))      # Output: False
print(bool(1))      # Output: True
print(bool(""))     # Output: False
print(bool("text")) # Output: True

Additional Notes

Casting may raise errors if the conversion is not possible. For example, trying to cast a string with non-numeric characters to an integer will result in a ValueError. Always ensure that the data being casted is compatible with the target type to avoid such errors.