getting a "NameError: name 'i' is not defined" error while compiling multiples of three python script

multiples_of_three = []
totals_of_threes = 0

while not (i > values.length):
        if (values[i] % 3) == 0:
                multiples_of_three[i] = values[i]

while True:
        if not multiples_of_three.empty():
                total_of_threes = total_of_threes + multiples_of_three.first_item
                multiples_of_three.remove_first_item
        elif multiples_of_three.empty():
                break
print(total_of_threes)

I am getting a "NameError: name 'i' is not defined" when running this python script and also seem there are other issues with the code.

1 answer

  • answered 2019-10-08 04:12 itypewithmyhands

    Based on your comment, I am guessing that perhaps you can simplify your approach a bit. In this example, I'm just using a list containing the input numbers, while you seem to be using an object of some unknown description.

    You can also use list comprehension equal to this for loop, but for readability I think the below would be a good starting point:

    values = [1,2,3,4,5,6,7,8,9,10,11,12,13,14,15]
    mult3x = []
    total3x = 0
    
    for val in values:
        if val % 3 == 0:
            mult3x.append(val)
    
    total3x = sum(mult3x)
    
    print('Input: {}'.format(values))
    print('Multiples of 3: {}'.format(mult3x))
    print('Total: {}'.format(total3x))
    
    > Input: [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15]
    > Multiples of 3: [3, 6, 9, 12, 15]
    > Total: 45