+ 4
Calculate Sum In List In Python
Please assist me with where I am going wrong with this quiz. I want to calculate the sum of even numbers in the list below. I am a newbie. items = [23, 555, 668, 123, 128, 4242, 990] sum = 0 n = 0 while n < len(items): if items[n] % 2 == 0: num = items[n] sum += num else: continue; n += 1 print(sum)
5 ответов
+ 3
Eric Khang'ati , remove the else part. Look at the code.
https://code.sololearn.com/chlddxVs1OlR/?ref=app
+ 6
Eric Khang'ati , there is also an other way to do this task by using a for loop. This is more convenient than using a while loop, because you don't need to know the length of the list, and you need no counter variable:
items = [23, 555, 668, 123, 128, 4242, 990]
total = 0
for num in items:
if num % 2 == 0:
total += num
print(total)
You also should avoid using the variable name "sum", as this is a built-in function and class of python. In some cases this will lead to problems.
+ 3
the continue statement in your else part stops every thing because continue skips everything which is after that and then run the loop again without the increment (because your increment is after continue)
+ 3
Lothar thank you. I really appreciate for this.
0
Thank you for your responses. After removing the else part it worked.