Adding odd numbers in a list

前端 未结 6 972
执笔经年
执笔经年 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:29

    May I suggest a small tweak to Martijn Pieter's excellent answer?

    To make your method more flexible, try incorporating range into the method. It will make your method able to sum the odd values in any list. Also, I switched up your method signature so that it conforms to the Python Style Guide PEP8, just being picky here:)

    def add_odd_numbers(max_list_value):
        numbers = range(0, max_list_value)
        total = 0
        for num in numbers:
            if num % 2 == 1:
                total += num
        return total
    
    if __name__ == '__main__':
        print add_odd_numbers(10)
    

提交回复
热议问题