DL_python
DL_python

Reputation: 33

Why does my while loop not sum all values

I am learning Python and having some trouble understanding While loop. I was trying to calculate the total of negative numbers, but couldn't get it right.

given_list3=[7,5,4,4,3,1,-2,-3,-5,-7]
total6=0
i=0
while i<len(given_list3)and given_list3[i]<0:
    total6+=given_list3[i]
    i+=1
print(total6)

Here is my code to calculate the sum of positive numbers (which works fine)

given_list=[5,4,4,3,1,-3,-4,-5]
total3=0
i=0
while i<len(given_list) and given_list[i]>0:
    total3+= given_list[i]
    i+=1
print(total3)

Upvotes: 1

Views: 428

Answers (2)

Mayowa Ayodele
Mayowa Ayodele

Reputation: 559

You can't use a while loop for this,

You have said while the condition is true, at the very first instance the condition is not true because 7 is not less than 0 so the condition stops.

You will need to use some other type of loop e.g for loop

given_list3=[7,5,4,4,3,1,-2,-3,-5,-7]
total6=0

i=0


for i in range(len(given_list3)):
    if(given_list3[i]<0):
        total6+=given_list3[i]


print(total6)

Upvotes: 0

Nick
Nick

Reputation: 147166

Your problem is that when you are calculating the sum of negative numbers, your while loop exits on the first value because it doesn't pass given_list3[i]<0 (the only reason your sum of positive numbers works is that the positive numbers are all at the beginning of the list). You should move that check into your loop for example:

while i<len(given_list3):
    if given_list3[i]<0:
        total6+=given_list3[i]
    i+=1

print(total6)

Output

-17

Note you can replace simple loops like that with a list comprehension e.g.

total6 = sum([x for x in given_list3 if x < 0])
print(total6)

Output

-17

Upvotes: 5

Related Questions