User-Friendly Guide to Adding Lists of Numbers in Python
School
University of Missouri, Columbia**We aren't endorsed by this school
Course
INFOTC 1040
Subject
Information Systems
Date
Dec 11, 2024
Pages
1
Uploaded by ColonelPencil14274
def get_list_from_user(prompt):"""Get a list of numbers from the user.Args:prompt (str): The prompt to display to the user.Returns:list: A list of numbers entered by the user."""while True:user_input = input(prompt)try:numbers = [float(num) for num in user_input.split(",")]return numbersexcept ValueError:print("Invalid input. Please enter a list of numbers separated by commas.")def add_lists_index_wise(lst1, lst2):"""Add two lists index-wise.Args:lst1 (list): The first list of numbers.lst2 (list): The second list of numbers.Returns:list: A new list where each item is the sum of the items at the corresponding indices in the two input lists."""if len(lst1) != len(lst2):raise ValueError("Lists must have the same length")result = []for i in range(len(lst1)):result.append(lst1[i] + lst2[i])return resultdef main():"""Main function to interact with the user."""while True:lst1 = get_list_from_user("Enter the first list of numbers (separated by commas): ")lst2 = get_list_from_user("Enter the second list of numbers (separated by commas): ")try:result = add_lists_index_wise(lst1, lst2)print("Result:", result)breakexcept ValueError as e:print(e)if __name__ == "__main__":main()