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)
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)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With