22, సెప్టెంబర్ 2025, సోమవారం

W10 ..........Python program that takes a dictionary input from the keyboard, then calculates and prints the sum of its values:

 # Function to take dictionary input from the user and calculate the sum of values

def sum_of_values():

    # Get dictionary input from the user as a string and convert it to a dictionary

    user_input = input("Enter a dictionary (e.g. {'a': 1, 'b': 2, 'c': 3}): ")

    

    # Safely evaluate the user input to a dictionary

    try:

        user_dict = eval(user_input)

        

        # Check if input is a valid dictionary

        if isinstance(user_dict, dict):

            # Calculate the sum of the dictionary values

            total_sum = sum(user_dict.values())

            print("The sum of the values in the dictionary is:", total_sum)

        else:

            print("Please enter a valid dictionary.")

    except Exception as e:

        print("Invalid input. Please enter a dictionary in correct format.")

        print("Error:", e)


# Call the function to execute

sum_of_values()


కామెంట్‌లు లేవు:

కామెంట్‌ను పోస్ట్ చేయండి