Type casting converts a variable from one data type to another. Python supports both implicit coercion (performed automatically by CPython during arithmetic operations) and explicit type casting using built-in constructor functions.
flowchart TD
A["Input Data"] --> B{"Automatic or Manual?"}
B -- "Automatic Coercion" --> C["Implicit Conversion (e.g. int + float -> float)"]
B -- "Manual Constructor" --> D["Explicit Conversion (e.g. str(10), int('42'))"]
D --> E{"Valid Conversion Syntax?"}
E -- "Yes" --> F["Target Type Object Created"]
E -- "No" --> G["Raises ValueError Exception"]
int(x): Converts integers, floats (truncates decimals), or numeric strings into an integer.float(x): Converts numbers or numeric strings into a floating-point number.str(x): Converts any object into its string representation via __str__().list(iterable), tuple(iterable), set(iterable): Convert collection sequences.from typing import Any, List, Union
def parse_user_input(raw_value: str) -> Union[int, float, str]:
"""Attempt to cast a raw string input into an integer, float, or fallback string."""
# Attempt integer casting
try:
return int(raw_value)
except ValueError:
pass
# Attempt float casting
try:
return float(raw_value)
except ValueError:
pass
# Fallback to string
return raw_value
if __name__ == "__main__":
test_inputs: List[str] = ["42", "3.14159", "Kodersolution", "0"]
for raw in test_inputs:
casted_val = parse_user_input(raw)
print(f"Raw String: '{raw}' -> Casted Result: {casted_val!r} ({type(casted_val).__name__})")
# Sequence conversion
raw_tuple = (1, 2, 2, 3)
unique_list = list(set(raw_tuple))
print(f"Tuple {raw_tuple} -> Deduplicated List: {unique_list}")
int(9.99)) truncates toward zero (yielding 9), rather than rounding. Use round(9.99) if rounding is needed.int("abc") raises ValueError. Always wrap dynamic string parsing in a try/except ValueError block.bool(0), bool(""), bool([]), and bool(None) evaluate to False; non-empty values evaluate to True.Write a function clean_numeric_list(items: list[Any]) -> list[float] that filters out items that cannot be cast to a float and returns a list of converted float values.
Sign in to track your learning journey, earn industry-recognized certificates, and join our elite developer community.
Quick Access With