0
Why I can't get the total of the odd nunber?
https://code.sololearn.com/c312m1EaD2UI/?ref=app Why the result always zero??
6 Answers
+ 9
It is ok to use the while loop, but it is much easier to do this task with a for loop. With a for loop, you dont't have to care about the length of the iterable and you don't need to use a counter variable.
items = [23, 555, 666, 123, 128, 4242, 990]
sum_ = 0
for num in items:
if num % 2 != 0:
sum_ += num
print(sum_)
# or with a comprehension:
print(sum([i for i in items if i % 2 != 0]))
+ 2
Joe Ma
items = [23, 555, 666, 123, 128, 4242, 990]
sum = 0
n = 0
while n < len(items):
num = items[n]
n+=1
if num % 2 == 0:
continue
else:
sum += num
print(sum)
+ 1
Show this code
https://code.sololearn.com/cs2U4f52tYBK/?ref=app
+ 1
sum = 0
n = 0
while n < len(items):
num = items[n]
if num % 2 != 0:
sum += num
n+=1
print(sum)
+ 1
Your num doesn't change at all. It remains to be the items[0] for the whole loop.
0
And move the else statement to the left of the code then it is called.