Adding odd numbers in a list

前端 未结 6 970
执笔经年
执笔经年 2021-01-01 03:37

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

6条回答
  •  别那么骄傲
    2021-01-01 04:31

    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
    

提交回复
热议问题