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)
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)
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.
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)
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)
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)
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.
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)