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 numbe
You could do this:
def addOddNumbers(numbers):
return sum(num for num in numbers if num % 2 == 1) # or use print instead of return
To print it if you use return, you would precede the function call with the print statement:
print addOddNumbers(numbers)
your statement return sum
just returns the sum
function(nothing else) and exits the addOddNumbers
function.
print sum(numbers)
actually just prints the sum of EVERY number in numbers:
you for loop if would need a variable to keep track of your total:
total = 0
for n in numbers:
if n % 2 == 1:
total += n # total accumulates the sum of all odd numbers then you can return or print it