Data Type Conversions

Carson West

Variables and Data Types

Data Type Conversions

Python offers various ways to convert data from one type to another. This is crucial for flexibility and performing operations requiring specific data types. Incorrect conversions can lead to errors.

Common Conversions:

int("10")  # Output: 10
int(10.7)  # Output: 10
int("10a") # Output: ValueError
float("10")  # Output: 10.0
float(10)   # Output: 10.0
float("10.5") # Output: 10.5
str(10)    # Output: "10"
str(10.5)  # Output: "10.5"
str(1,2,3) # Output: "1, 2, 3"
bool(1)    # Output: True
bool(0)    # Output: False
bool("")   # Output: False
bool("hello") # Output: True
bool(1)   # Output: False
list((1,2,3)) # Output: 1, 2, 3
list("abc")   # Output: ['a', 'b', 'c']]

Type Errors:

Attempting to convert incompatible types will raise a TypeError. For example:

int("ten")  # Raises TypeError

Explicit vs. Implicit Conversions:

Python can sometimes perform implicit type conversions (e.g., adding an integer and a float automatically results in a float). However, explicit conversions using the functions above are generally preferred for clarity and to avoid unexpected behavior.

Error Handling (Type Hinting)

Advanced Conversions:

JSON Conversion