Python Forum

Full Version: while loop question
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
Hello everyone,

I am a beginner of Python and I have some questions regarding how to use while loop. I would like to calculate the sum of all the negative values from the lists below.

For list b, the codes stops after the first item; for list a, the list stops after item 6. My codes are below. It works only when the negative numbers are consecutive. Not sure what needs to change in order to achieve my goals.

Thank you

Best,
Andy

b = [-3, 4, 6, 7, -10, -3, 8, -4]
total2 = 0
j = 0
while b[j] > 0:
        j += 1
while b[j] < 0:
        total2 += b[j]
        j += 1
print(total2)
///
the result is -3
-----------------------------
a = [3, 4, 6, 7, -10, -3, 8, -4]
total3 = 0
j = 0
while a[j] > 0:
        j += 1
while a[j] < 0:
        total3 += [j]
        j += 1
print(total3)
///
the result is -13
Please use code tags. I added them for you this time, but check the BBCode link in my signature below to learn how to do it yourself.

You should just do a for loop over the items in the list, and only add them to the total if the item is less than zero.
To clarify why the while loops are failing: You get out of the first while loop when the sign changes. You have no way to get back to it when the sign changes back.
Thanks for the clarification and editing.
just to mention that using while in this case/this way is how to say ... unusual

if you have to use while loop, although not recommended
my_list = [-3, 4, 6, 7, -10, -3, 8, -4]
total = 0
j = 0
while j < len(my_list):
    if my_list[j] < 0:
        total += my_list[j]
    j += 1
print(total)
two more pythonic ways, there are also others:
my_list = [-3, 4, 6, 7, -10, -3, 8, -4]
total = 0
for number in my_list:
    if number < 0:
        total += number
print(total)
my_list = [-3, 4, 6, 7, -10, -3, 8, -4]
print(sum(number for number in my_list if number < 0))