Python Forum

Full Version: Use of function/return
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
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))
Now my question is:
Is there any better way to re-code the above using function definition / return, e.g.
def add_up_the_odds(numbers):
return

Thanks!!
Yes you could code it as a function, give it a go and if you have any problems ask about where you are going wrong.
I tried with this then:

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))
I'm not getting any result, it looks that "odds is not defined", but I defined it at the beginning of the function, what's wrong with this code?
You didn't call the function add_up_the_odds
Do you mean the below?

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


It didn't work
Here is an example of using a function
def a_function(function_input):
    local_variable = "Local Variable"
    return f"{function_input} + {local_variable}"


returned_from_function = a_function("Function Input")

print(returned_from_function)
Output:
Function Input + Local Variable

The code doesn't need to be changed much to turn it into a function
numbers = [1, 5, 3, 2]
print(numbers)


def get_odd_numbers(numbers):
    odd_numbers = []
    for number in numbers:
        if number % 2:
            odd_numbers.append(number)
    return odd_numbers


odd_numbers = get_odd_numbers(numbers)
print(odd_numbers)
print(sum(odd_numbers))
Output:
[1, 5, 3, 2] [1, 5, 3] 9

It can also be written as the more compact
def get_odd_numbers(numbers):
    return [number for number in numbers if number % 2]
OK many thanks, that's incredibly short, very nice.

In the meantime I managed to do the below, trying to follow your suggestions, to me it looks working fine, much more complicated than your for sure.

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