Type Conversion (Casting)
What is Type Conversion?
Type conversion, or casting, is the process of converting a variable from one data type to another. In Python, this is often necessary when you need to perform operations between different data types or when you need to ensure data is in the appropriate format for specific operations.
Built-in Functions for Type Conversion
Python provides several built-in functions for converting data types. Here are some of the most commonly used ones:
- 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.
Converting to Integers
The int() function converts a value to an integer. It can be used with different types of values, including strings and floating-point numbers.
Examples
From Float to Integer
float_value = 3.99 int_value = int(float_value) # Converts to 3 print(int_value) # Output: 3
From String to Integer
string_value = "123" int_value = int(string_value) # Converts to 123 print(int_value) # Output: 123
Note: The string must represent a valid integer. Otherwise, it will raise a ValueError.
invalid_string = "123.45" int_value = int(invalid_string) # This will raise a ValueError
Converting to Floats
The float() function converts a value to a floating-point number.
Examples
From Integer to Float
int_value = 10 float_value = float(int_value) # Converts to 10.0 print(float_value) # Output: 10.0
From String to Float
string_value = "12.34" float_value = float(string_value) # Converts to 12.34 print(float_value) # Output: 12.34
Note: The string must represent a valid floating-point number. Otherwise, it will raise a ValueError.
invalid_string = "abc" float_value = float(invalid_string) # This will raise a ValueError
Converting to Strings
The str() function converts a value to a string. This is useful when you want to concatenate or display values in a textual format.
Examples
From Integer to String
int_value = 42 string_value = str(int_value) # Converts to "42" print(string_value) # Output: "42"
From Float to String
float_value = 3.14159 string_value = str(float_value) # Converts to "3.14159" print(string_value) # Output: "3.14159"
Converting to Booleans
The bool() function converts a value to a boolean (True or False). In Python, certain values are inherently considered as False, such as 0, 0.0, ” (empty string), [] (empty list), and None. All other values are considered True.
Examples
From Integer to Boolean
zero = 0 non_zero = 1 print(bool(zero)) # Output: False print(bool(non_zero)) # Output: True
From String to Boolean
empty_string = "" non_empty_string = "Hello" print(bool(empty_string)) # Output: False print(bool(non_empty_string)) # Output: True
Combining Type Conversion
Sometimes, you need to combine multiple type conversions. For example, converting a string to an integer and then to a float:
string_value = "12.34" int_value = int(float(string_value)) # First convert to float, then to int print(int_value) # Output: 12
Error Handling in Type Conversion
When converting between types, especially with user input, it’s essential to handle potential errors gracefully. For example:
user_input = "abc" try: number = int(user_input) except ValueError: print("The input is not a valid integer.")
This ensures that your program can handle unexpected input without crashing.
Practical Examples
Here are some practical examples that illustrate type conversion:
Example 1: Calculating the average of numbers given as strings
num1 = "10" num2 = "20" num3 = "30" average = (int(num1) + int(num2) + int(num3)) / 3 print(f"The average is: {average}")
Example 2: Formatting a float to a string with two decimal places
float_value = 3.14159 formatted_string = "{:.2f}".format(float_value) # Converts to "3.14" print(f"Formatted float: {formatted_string}")
Example 3: Checking user input
user_input = input("Enter a number: ") try: number = float(user_input) print(f"You entered the number: {number}") except ValueError: print("That's not a valid number.")