Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Adding odd numbers in a list

Tags:

python

I am trying to find the sum of all odd numbers within a given range but I cannot figure out how to specify which numbers are odd. My professor said to use "for num in numbers" to access the elements in the range. This is what I have so far.

numbers = range(0, 10)

def addOddNumbers(numbers):
    for num in numbers:
        if num % 2 == 1:
            return sum
        print sum(numbers)

if __name__ == '__main__':
    addOddNumbers(numbers)
like image 932
PhysicsLemur Avatar asked Oct 02 '22 01:10

PhysicsLemur


1 Answers

You were nearly there; using num % 2 is the correct method to test for odd and even numbers.

return exits a function the moment it is executed. Your function returns when the first odd number is encountered.

Don't use sum() if you use a loop, just add the numbers directly:

def addOddNumbers(numbers):
    total = 0
    for num in numbers:
        if num % 2 == 1:
            total += num
    print total

You could first build a list of odd numbers for sum():

def addOddNumbers(numbers):
    odd = []
    for num in numbers:
        if num % 2 == 1:
            odd.append(num)
    print sum(odd)

For sum(), you can use a generator expression:

def addOddNumbers(numbers):
    print sum(num for num in numbers if num % 2 == 1)
like image 68
Martijn Pieters Avatar answered Oct 13 '22 10:10

Martijn Pieters