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
- Inputs:
valueis the text"42", two characters (the digits 4 and 2), andtarget_typeis the label"int", naming the kind of value to hand back. - Math: reading those digits as a base-10 numeral gives , a whole number.
- Output: the integer
42. Printed, it looks identical to the input, but it is now a number: adding 1 gives 43, whereas gluing a "1" onto the text would give "421". - The same input with the other targets: as a float it becomes , as a string it stays "42", and as a boolean it is True, because any non-empty text counts as true.
- A float like requested as an integer loses its fractional part (it moves toward zero), giving 3, not the rounded 4.
- Text that is not a whole-number numeral, such as "abc" or "4.2", cannot become an integer, so the function returns the string "Error" instead of crashing.
Constraints
- Handle conversion errors gracefully
- target_type will be one of: "int", "float", "str", "bool"