Use of function/return

Hello all,

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?

You have:

for number in range ( 1 , len (numbers)):

Remember that the index of the first element in a list is 0.

1 Like

Besides turning it into a function, you changed what you were doing.

In the first program you used:

for number in numbers:

Here number is set to each of the elements of the list in turn. So you can add them up (although it’s unclear why you couldn’t have just summed the original numbers in the first place).

But in your function you run:

for number in range ( 1 , len (numbers)):

This just returns numbers in a row (1, 2, 3, …). The actual contents of numbers is never examined.

2 Likes