pythonif-statement

Multiples of 3 or 5 Can this be done using else if statements?


I've tried the following code and it works fine except for 0 or negative numbers, it says: "cannot access local variable 'add_list' where it is not associated with a value".

I've seen how this can be done other ways I'm just wondering if it can be done using an elif statement. I've tried "break", indentation and different orders but get the same error.

def solution(number):
    raw_list = range(number)
    my_list = []
    for num in raw_list:
        if num < 0:
            my_list.append(0)
            return my_list 
        elif num % 3 == 0 or num % 5 == 0:
            my_list.append(num)
            add_list = sum(my_list)
    return add_list

Solution

  • If the range doesn't contain any multiples of 3 or 5, you never execute add_list = sum(my_list). As a result, you get an error when you try to return it.

    There's no need to calculate the sum each time through the loop, since you're overwriting the sum from the previous iteration. Take that out of the loop, then it won't be dependent on the elif condition.

    def solution(number):
        raw_list = range(number)
        my_list = []
        for num in raw_list:
            if num < 0:
                my_list.append(0)
                return my_list 
            elif num % 3 == 0 or num % 5 == 0:
                my_list.append(num)
        add_list = sum(my_list)
        return add_list
    

    Since the if condition can never be true, you could also leave that out. Then you can simplify the whole thing to:

    def solution(number):
        return sum(num in range(number) if num % 3 == 0 or num % 5 == 0)
    

    BTW, raw_list is a poor name for the variable. range() doesn't return a list, it returns a range object that acts as an generator.