From f18ac10dd570840a6f53536c78d0455039cb3c22 Mon Sep 17 00:00:00 2001 From: Rathinavel706 <166843671+Rathinavel706@users.noreply.github.com> Date: Fri, 31 Oct 2025 16:38:14 +0530 Subject: [PATCH] type conversion Python type conversion is the process of changing the data type of a variable from one type to another such as converting an integer to a string or a float. --- Type Conversion and Validation | 38 ++++++++++++++++++++++++++++++++++ 1 file changed, 38 insertions(+) create mode 100644 Type Conversion and Validation diff --git a/Type Conversion and Validation b/Type Conversion and Validation new file mode 100644 index 00000000..5004df1c --- /dev/null +++ b/Type Conversion and Validation @@ -0,0 +1,38 @@ +def get_valid_input(prompt, target_type): + while True: + user_input = input(prompt) + try: + + if target_type == int: + return int(user_input) + elif target_type == float: + return float(user_input) + elif target_type == str: + return str(user_input) + elif target_type == bool: + if user_input.lower() in ['true', '1', 'yes']: + return True + elif user_input.lower() in ['false', '0', 'no']: + return False + else: + raise ValueError("Invalid boolean value.") + except ValueError: + print(f" Invalid input! Please enter a valid {target_type.__name__} value.") + +print("=== Type Conversion and Validation Example ===") +num_int = get_valid_input("Enter an integer: ", int) +num_float = get_valid_input("Enter a floating-point number: ", float) +text = get_valid_input("Enter a string: ", str) +bool_val = get_valid_input("Enter a boolean value (True/False): ", bool) + +print("\n Conversion Results:") +print(f"Integer Value: {num_int} (Type: {type(num_int)})") +print(f"Float Value: {num_float} (Type: {type(num_float)})") +print(f"String Value: '{text}' (Type: {type(text)})") +print(f"Boolean Value: {bool_val} (Type: {type(bool_val)})") + +print("\n Additional Type Conversions:") +print(f"Integer to Float: {float(num_int)}") +print(f"Float to Integer: {int(num_float)}") +print(f"Integer to String: '{str(num_int)}'") +print(f"String to Uppercase: '{text.upper()}'")