Search code examples
functionreturn

Use of function / return


I had the task to code the following:

Take a list of integers and returns the value of these numbers added up, but only if they are odd.

Example input: [1,5,3,2] Output: 9 I did the code below and it worked perfectly.


numbers = [1,5,3,2]
print(numbers)
add_up_the_odds = []
for number in numbers:
    if number % 2 == 1:
        add_up_the_odds.append(number)
print(add_up_the_odds)
print(sum(add_up_the_odds))

Then I tried to re-code it using function definition / return:


def add_up_the_odds(numbers):
    odds = []
    for number in range(1,len(numbers)):
      if number % 2 == 1:
          odds.append(number)
    return odds
numbers = [1,5,3,2]
print (sum(odds))

But I couldn’t make it working, anybody can help with that?


Solution

  • Note: I'm going to assume Python 3.x

    It looks like you're defining your function, but never calling it.

    When the interpreter finishes going through your function definition, the function is now there for you to use - but it never actually executes until you tell it to.

    Between the last two lines in your code, you need to call add_up_the_odds() on your numbers array, and assign the result to the odds variable.

    i.e. odds = add_up_the_odds(numbers)