v9.1.1
Menu

Type Converter

easyFREEVariables & TypesPython BasicsPython Foundations

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

Input
value = "42", target_type = "int"
Output
42
Reasoning
  • Inputs: value is the text "42", two characters (the digits 4 and 2), and target_type is the label "int", naming the kind of value to hand back.
  • Math: reading those digits as a base-10 numeral gives 4×101+2×100=40+2=424 \times 10^1 + 2 \times 10^0 = 40 + 2 = 42, 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 42.042.0, as a string it stays "42", and as a boolean it is True, because any non-empty text counts as true.
  • A float like 3.73.7 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"

Learn this in

More from Python Foundations

solution.py

Test results

Sign in to run your code against the test cases.