Python Basics: Type Conversion
Type conversion, also known as type casting, is the process of changing one data type into another in Python. This is often necessary because Python is a strongly-typed language, meaning it enforces data types. You can't directly perform operations between incompatible types (e.g., adding a string to an integer).
Why is Type Conversion Important?
- Data Compatibility: Allows you to perform operations on data of different types.
- User Input: User input from functions like
input()is always a string. You often need to convert it to an integer or float for calculations. - Data Processing: Sometimes data comes in one format and needs to be transformed for analysis or storage.
- Avoiding Errors: Prevents
TypeErrorexceptions that occur when you try to perform operations on incompatible types.
Built-in Type Conversion Functions
Python provides several built-in functions for type conversion:
int(): Converts a value to an integer.- Can convert strings, floats, and other numeric types.
- If converting a string, the string must represent a valid integer.
- If a float is converted, the decimal part is truncated (removed).
x = "10" y = 3.14 z = int(x) # z becomes 10 (string to integer) a = int(y) # a becomes 3 (float to integer - truncation) print(type(z)) # Output: <class 'int'> print(type(a)) # Output: <class 'int'>float(): Converts a value to a floating-point number.- Can convert strings, integers, and other numeric types.
- If converting a string, the string must represent a valid floating-point number.
x = "3.14" y = 5 z = float(x) # z becomes 3.14 (string to float) a = float(y) # a becomes 5.0 (integer to float) print(type(z)) # Output: <class 'float'> print(type(a)) # Output: <class 'float'>str(): Converts a value to a string.- Can convert any data type to a string representation.
x = 10 y = 3.14 z = True a = str(x) # a becomes "10" (integer to string) b = str(y) # b becomes "3.14" (float to string) c = str(z) # c becomes "True" (boolean to string) print(type(a)) # Output: <class 'str'> print(type(b)) # Output: <class 'str'> print(type(c)) # Output: <class 'str'>bool(): Converts a value to a boolean (True or False).- Most values are considered
Trueexcept:0(zero)0.0(zero float)""(empty string)[](empty list)()(empty tuple){}(empty dictionary)None
x = 10 y = 0 z = "Hello" a = bool(x) # a becomes True b = bool(y) # b becomes False c = bool(z) # c becomes True print(type(a)) # Output: <class 'bool'> print(type(b)) # Output: <class 'bool'> print(type(c)) # Output: <class 'bool'>- Most values are considered
list(): Converts an iterable (e.g., string, tuple, set) to a list.x = "hello" y = (1, 2, 3) z = list(x) # z becomes ['h', 'e', 'l', 'l', 'o'] a = list(y) # a becomes [1, 2, 3] print(type(z)) # Output: <class 'list'> print(type(a)) # Output: <class 'list'>tuple(): Converts an iterable to a tuple.x = [1, 2, 3] y = "world" z = tuple(x) # z becomes (1, 2, 3) a = tuple(y) # a becomes ('w', 'o', 'r', 'l', 'd') print(type(z)) # Output: <class 'tuple'> print(type(a)) # Output: <class 'tuple'>set(): Converts an iterable to a set. Sets only contain unique elements.x = [1, 2, 2, 3, 3, 3] y = "banana" z = set(x) # z becomes {1, 2, 3} a = set(y) # a becomes {'b', 'a', 'n'} print(type(z)) # Output: <class 'set'> print(type(a)) # Output: <class 'set'>dict(): Converts a sequence of key-value pairs (e.g., a list of tuples) to a dictionary.x = [("a", 1), ("b", 2), ("c", 3)] y = dict(x) # y becomes {'a': 1, 'b': 2, 'c': 3} print(type(y)) # Output: <class 'dict'>
Example: User Input and Type Conversion
age_str = input("Enter your age: ") # Input is always a string
try:
age = int(age_str) # Convert the string to an integer
print("You are", age, "years old.")
except ValueError:
print("Invalid input. Please enter a valid integer for your age.")
Important Considerations:
- Error Handling: Type conversion can raise errors if the value cannot be converted to the target type (e.g., trying to convert "abc" to an integer). Use
try-exceptblocks to handle these errors gracefully. - Data Loss: Converting a float to an integer truncates the decimal part. Be aware of potential data loss.
- String Formatting: When converting numbers to strings, consider using f-strings or the
.format()method for more control over the output format. (This is a more advanced topic, but important for presentation).
This covers the basics of type conversion in Python. Understanding these concepts is crucial for writing robust and reliable Python programs.