Geeniee
Geeniee

Reputation: 107

sum only the odd numbers in the list, easy to do with for loop but how about while loop?

I tried writing this for this specific list but it keeps crashing, what can I change?

items = [23, 555, 666, 123, 128, 4242, 990]
summa = 0
n = 0
while n < len(items):
   num = items[n]
   if num % 2 != 0:
      continue
   summa += num
   n += 1
print(summa)

Upvotes: 0

Views: 645

Answers (6)

Bhagyesh Dudhediya
Bhagyesh Dudhediya

Reputation: 1856

Here is the code for you:

items = [23, 555, 666, 123, 128, 4242, 990,1]
summa = 0
n = 0

while n < len(items):
    summa += items[n] if items[n]%2 != 0 else 0
    n+=1
print (summa)

Upvotes: 0

Code With Faraz
Code With Faraz

Reputation: 62

There is no use of continue keyword. Just remove it and if the number is odd then add it to summa else do nothing. In both cases the value of n is incremented by 1 because it is outside the if block.

items = [23, 555, 666, 123, 128, 4242, 990]
summa = 0
n = 0
while n < len(items):
    num = items[n]
    if num % 2 != 0:
        summa += num
    n += 1
print(summa)

This is the output you will get 701.

Screenshot of code and output

Upvotes: 0

sam2611
sam2611

Reputation: 455

You need not to put continue it just keeps looping through while without incrementing the value of n. Instead do the below changes:

items = [23, 555, 666, 123, 128, 4242, 990]
summa = 0
n = 0
while n < len(items):
   num = items[n]
   if num % 2 != 0:
      summa += num
   n += 1
print(summa)

Upvotes: 1

Guy
Guy

Reputation: 50809

As the other answers as pointed out n += 1 is never reached when the if is true, so you have an infinite loop.

Instead of while loop you can use generator expression

print(sum(item for item in items if item % 2)) # 701

Upvotes: 3

fusion
fusion

Reputation: 457

You should increment n in your if block as well.

if num % 2 != 0:
  n += 1
  continue

EDIT:
As mentioned in the comment, the cleaner solution would be to increment n before the if block, to prevent duplicate code:

while n < len(items):
   num = items[n]
   n += 1
   if num % 2 != 0:
      continue
   summa += num
print(summa)

Upvotes: 1

Taner
Taner

Reputation: 1

You forgot to count up if num % 2 != 0

items = [23, 555, 666, 123, 128, 4242, 990]
summa = 0
n = 0
while n < len(items):
   num = items[n]
   if num % 2 != 0:
      n += 1
      continue
   summa += num
   n += 1
   print(summa)

Upvotes: 0

Related Questions