Variable Casting

Variable Casting

Tags: Math Basics

Credit: CodingChallenge

Difficulty: Beginner

Type: Text

Category: Practice

Time Allowed: 5 s

Description:

Write a function that takes two parameters: a value and a type to cast to. The function should cast the input value to the specified type and return the result. This problem is designed to help you practice variable casting and type conversion between numbers, strings, and booleans.

Constraints:

  • The input value can be a string, integer, float, or boolean.
  • The type to cast to will be a string specifying the target type: "int", "float", "str", or "bool".
  • The function should return the value cast to the specified type.

Examples:

  • Input: ("123", "int")

  • Output: 123 (integer)

  • Input: (45, "str")

  • Output: "45" (string)

  • Input: ("True", "bool")

  • Output: True (boolean)

  • Input: (0, "bool")

  • Output: False (boolean)

Test Case Input Expected Output
1 ["123", "int"] 123
2 ["45.67", "float"] 45.67
3 [True, "str"] "True"
4 [0, "bool"] False
5 ["", "bool"] False
6 ["False", "bool"] True
7 [123, "str"] "123"
8 [3.14, "int"] 3
9 ["True", "bool"] True
10 [False, "int"] 0
11 [True, "int"] 1
12 ["100", "float"] 100.0

Please register or login to submit solutions to challenges.