Help with assignment

Discussion in 'Python' started by beginner_python, Nov 6, 2022.

  1. beginner_python

    beginner_python New Member

    Joined:
    Sep 27, 2022
    Messages:
    3
    Likes Received:
    1
    Trophy Points:
    3
    Gender:
    Male
    I am having trouble with a homework assignment. The task is to "Write a function called double_it() that takes a list as a parameter. The function should iterate through the list and multiply each numeric element in the original list by 2. Assume that the list only contains numeric (int or float) values. Return of elements that were doubled". I am having trouble though and do not know why. This is the code I have so far.
    Code:
    def main():
        user_list = input("Enter a list of only numbers.")
        user_list_1 = [user_list]
        new_list = double_it(user_list_1)
        print(new_list)
    
    def double_it(list_user):
        for index in range(len(list_user)):
            element = list_user[index]
            if element != " " or element != ",":
                number = int(list_user[index])
                list_user[index] *= 2
              
        return list_user
      
    main()
    
     
  2. syevale111

    syevale111 New Member

    Joined:
    Jun 27, 2023
    Messages:
    1
    Likes Received:
    0
    Trophy Points:
    1
    Gender:
    Male
    Home Page:
    https://www.sevenmentor.com/best-python-classes-in-pune.php
    You can get help from SevenMentor Python Course.
     
  3. kirsten Jacks

    kirsten Jacks New Member

    Joined:
    Apr 4, 2024
    Messages:
    2
    Likes Received:
    0
    Trophy Points:
    1
    Here you go, As per my understanding:

    def double_it(numbers):
    """Doubles the numeric elements in a list and returns a new list with the doubled values.

    Args:
    numbers: A list of numeric (int or float) values.

    Returns:
    A new list containing the doubled numeric elements from the original list.
    """

    doubled_list = []
    for num in numbers:
    # Check if the current element is numeric (int or float)
    if isinstance(num, (int, float)):
    doubled_list.append(num * 2)
    return doubled_list

    # Example usage
    my_list = [1, 2.5, "apple", 4]
    doubled_numbers = double_it(my_list)
    print(doubled_numbers) # Output: [2, 5.0, 8]
     

Share This Page

  1. This site uses cookies to help personalise content, tailor your experience and to keep you logged in if you register.
    By continuing to use this site, you are consenting to our use of cookies.
    Dismiss Notice