Type Converter
Problem Statement
Convert values between different Python types.
Background
Python provides built-in functions for type conversion:
- int(x) - convert to integer
- float(x) - convert to float
- str(x) - convert to string
- bool(x) - convert to boolean
Your Task
Write a function convert_value(value, target_type) that converts the value to the specified type.
Input
- value: Any Python value
- target_type: String indicating target type ("int", "float", "str", "bool")
Output Format
Return the converted value, or "Error" if conversion fails.
Example:
value = "42", target_type = "int"
42
int("42") converts the string "42" to integer 42
Constraints:
- Handle conversion errors gracefully
- target_type will be one of: "int", "float", "str", "bool"
Background Knowledge
Python is a dynamically typed language, meaning variables don't require explicit type declarations—the interpreter determines types at runtime based on assigned values. This flexibility aids rapid development but can lead to runtime errors from unintended type mismatches. Type conversion (or casting) explicitly changes a value's type using built-in functions like int(), float(), str(), and bool(), enabling operations across types (e.g., converting a string "42" to integer 42 for arithmetic).
These functions handle common conversions safely but raise ValueError or TypeError on invalid inputs (e.g., int("abc") fails). Understanding truthiness is key for bool(): falsy values include False, 0, 0.0, "", None, and empty collections; all others are truthy. This problem builds foundational skills in error handling and conditional logic, essential for robust Python functions.
Algorithm/Approach
Use a mapping-based dispatch pattern: create a dictionary linking target type strings to conversion functions, then attempt the conversion with exception handling. This avoids lengthy if-elif chains, promotes readability, and scales easily. Wrap the attempt in a try-except block to catch conversion failures, returning the result or "Error".
Step-by-Step Strategy
- Define the type mapping: Create a dictionary where keys are type strings ("int", "float", etc.) and values are the corresponding functions (int, float, etc.).
- Check input validity: Verify target_type exists in the mapping; if not, return "Error".
- Attempt conversion: Use try-except to call the mapped function on value.
- Handle success/failure: Return the converted value on success; return "Error" on ValueError, TypeError, or other exceptions.
- Test edge cases: Consider inputs like None, empty strings, or non-string numerics.
Common Pitfalls
- Forgetting exceptions: Not all conversions succeed (e.g., int("3.14") raises ValueError); always use try-except.
- Truthy surprises: bool("0") is True (non-empty string), but bool(0) is False—review falsy rules.
- Type string mismatches: Inputs may have extra whitespace or wrong case; consider .strip().lower() normalization.
- Mutable inputs: Avoid modifying value; conversions create new objects.
- Overly broad except: Catch only relevant exceptions (ValueError, TypeError) to avoid masking unrelated errors.
Time & Space Complexity
Time: O(1) average-case—dictionary lookup and function call are constant time, regardless of input size. Space: O(1)—fixed-size dictionary and minimal temporary objects for conversion.