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

22nd Dec 2020, 4:52 PM
Eric Khang'ati
Eric Khang'ati - avatar
5 ответов
+ 3
Eric Khang'ati , remove the else part. Look at the code. https://code.sololearn.com/chlddxVs1OlR/?ref=app
22nd Dec 2020, 5:01 PM
TheWh¡teCat 🇧🇬
TheWh¡teCat 🇧🇬 - avatar
+ 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.
22nd Dec 2020, 5:37 PM
Lothar
Lothar - avatar
+ 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)
22nd Dec 2020, 5:01 PM
Krish
Krish - avatar
+ 3
Lothar thank you. I really appreciate for this.
22nd Dec 2020, 5:40 PM
Eric Khang'ati
Eric Khang'ati - avatar
0
Thank you for your responses. After removing the else part it worked.
22nd Dec 2020, 5:30 PM
Eric Khang'ati
Eric Khang'ati - avatar