How to find sum of all values divisible by 3 in the list using while loop

Question:

I’m trying to find sum of all values divisible by 3 in the num_list = [1, 3, 4, 6, 8, 9, 11, 13, 15, 16, 17, 18] using while loop.

I’m trying to get 51. I tried something to get 51 but i don’t get it.

total = 0
 
list = [1, 3, 4, 6, 8, 9, 11, 13, 15, 16, 17, 18]

while list % 3 == 0:
    total += list
    print (total)
Asked By: forzakot

||

Answers:

total = 0
nums = [1, 3, 4, 6, 8, 9, 11, 13, 15, 16, 17, 18]
for num in nums:
    if num % 3 == 0:
        total += num
print(total)

But since you need to use a while loop:

total = 0
nums = [1, 3, 4, 6, 8, 9, 11, 13, 15, 16, 17, 18]
index = 0
while index < len(nums):
    num = nums[index]
    if num % 3 == 0:
        total += num
    index = index + 1
print(total)
Answered By: Kenny
total = 0
 
list = [1, 3, 4, 6, 8, 9, 11, 13, 15, 16, 17, 18]

for i in list:
    if i % 3 == 0:
        total += i
print(total)

you would have to iterate through the list using a for loop as this is the easiest way.

Answered By: Anton Chernyshov

Optimize way

nums = [1, 3, 4, 6, 8, 9, 11, 13, 15, 16, 17, 18]
total = sum(num for num in nums if num % 3 == 0)
print(total)
Answered By: Prashant Pansuriya
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.