Type Conversion
5 min ยท The Basics
Type Conversion
Type conversion (also called type casting) is the process of converting a value from one data type to another. Python provides built-in functions that allow you to explicitly convert between different types.
This is especially important when working with user input (which is always a string) or when you need to perform operations that require specific types.
Basic Type Conversions
Python provides several conversion functions. Here are the most common ones:
Common Conversion Functions
Here are the most frequently used conversion functions with examples:
int(x)โ Convert to integer (removes decimal part)float(x)โ Convert to floating-point numberstr(x)โ Convert to string representationbool(x)โ Convert to boolean (True/False)list(x)โ Convert iterable to listtuple(x)โ Convert iterable to tuple
String to Number Conversions
Converting strings to numbers is common when dealing with user input or reading from files:
Number to String Conversions
Converting numbers to strings is useful for displaying values or formatting output:
Boolean Conversions
Python has specific rules for what evaluates to True and False:
Error Handling with Conversions
Converting invalid values will raise errors. It's important to handle these cases:
Implicit vs Explicit Conversion
Python sometimes converts types automatically (implicit), but explicit conversion is clearer:
โ ๏ธ Common Conversion Errors
โข int("12.5") will fail - must use float("12.5") first, then int()
โข int("hello") will fail - string must contain valid number
โข Converting None to int/float will fail
โข Always validate or use try/except when converting user input!
Practical Example: Safe Input Conversion
Here's a pattern for safely converting user input: