Python Summing Neg Values using While LoopCalling an external command in PythonWhat are metaclasses in...

Can a rocket refuel on Mars from water?

Today is the Center

How to draw the figure with four pentagons?

How can I tell someone that I want to be his or her friend?

Is it possible to run Internet Explorer on OS X El Capitan?

Has there ever been an airliner design involving reducing generator load by installing solar panels?

What's the point of deactivating Num Lock on login screens?

What reasons are there for a Capitalist to oppose a 100% inheritance tax?

Can one be a co-translator of a book, if he does not know the language that the book is translated into?

Could gravitational lensing be used to protect a spaceship from a laser?

Were any external disk drives stacked vertically?

Western buddy movie with a supernatural twist where a woman turns into an eagle at the end

What killed these X2 caps?

SSH "lag" in LAN on some machines, mixed distros

Why is it a bad idea to hire a hitman to eliminate most corrupt politicians?

Why are electrically insulating heatsinks so rare? Is it just cost?

Took a trip to a parallel universe, need help deciphering

Brothers & sisters

I Accidentally Deleted a Stock Terminal Theme

Twin primes whose sum is a cube

What does it mean to describe someone as a butt steak?

Does a druid starting with a bow start with no arrows?

Why is Collection not simply treated as Collection<?>

Watching something be written to a file live with tail



Python Summing Neg Values using While Loop


Calling an external command in PythonWhat are metaclasses in Python?Finding the index of an item given a list containing it in PythonHow can I safely create a nested directory in Python?Does Python have a ternary conditional operator?Accessing the index in 'for' loops?How do I sort a dictionary by value?Emulate a do-while loop in Python?Iterating over dictionaries using 'for' loopsDoes Python have a string 'contains' substring method?






.everyoneloves__top-leaderboard:empty,.everyoneloves__mid-leaderboard:empty,.everyoneloves__bot-mid-leaderboard:empty{ height:90px;width:728px;box-sizing:border-box;
}







0















I am trying to write a code using while loop to sum all the negative numbers in a list. I am getting -10 instead of -17. Any idea why? Thanks!



# sum all the negative numbers using a while loop
given_list3 = [7, 5, 4, 4, 3, 1, -2, -3, -5 ,-7]
total6 = 0
i = 0
while -1 < 0:
total6 += given_list3[i]
i += -1
if given_list3[i] > 0:
break
print(total6)









share|improve this question















migrated from superuser.com 10 hours ago


This question came from our site for computer enthusiasts and power users.

























    0















    I am trying to write a code using while loop to sum all the negative numbers in a list. I am getting -10 instead of -17. Any idea why? Thanks!



    # sum all the negative numbers using a while loop
    given_list3 = [7, 5, 4, 4, 3, 1, -2, -3, -5 ,-7]
    total6 = 0
    i = 0
    while -1 < 0:
    total6 += given_list3[i]
    i += -1
    if given_list3[i] > 0:
    break
    print(total6)









    share|improve this question















    migrated from superuser.com 10 hours ago


    This question came from our site for computer enthusiasts and power users.





















      0












      0








      0








      I am trying to write a code using while loop to sum all the negative numbers in a list. I am getting -10 instead of -17. Any idea why? Thanks!



      # sum all the negative numbers using a while loop
      given_list3 = [7, 5, 4, 4, 3, 1, -2, -3, -5 ,-7]
      total6 = 0
      i = 0
      while -1 < 0:
      total6 += given_list3[i]
      i += -1
      if given_list3[i] > 0:
      break
      print(total6)









      share|improve this question
















      I am trying to write a code using while loop to sum all the negative numbers in a list. I am getting -10 instead of -17. Any idea why? Thanks!



      # sum all the negative numbers using a while loop
      given_list3 = [7, 5, 4, 4, 3, 1, -2, -3, -5 ,-7]
      total6 = 0
      i = 0
      while -1 < 0:
      total6 += given_list3[i]
      i += -1
      if given_list3[i] > 0:
      break
      print(total6)






      python






      share|improve this question















      share|improve this question













      share|improve this question




      share|improve this question








      edited 10 hours ago









      Nishant

      9,346124259




      9,346124259










      asked 11 hours ago









      JonnyChimpoJonnyChimpo

      1




      1




      migrated from superuser.com 10 hours ago


      This question came from our site for computer enthusiasts and power users.









      migrated from superuser.com 10 hours ago


      This question came from our site for computer enthusiasts and power users.


























          4 Answers
          4






          active

          oldest

          votes


















          1














          Various thing wrong




          • the -1 < 0 does not make sense, it wont terminate

          • you break when you find the first negative element


          You should do something like



          index = 0

          while index < len(lst):
          value = lst[index]

          if value > 0:
          continue

          total += value

          index += 1


          Note that, in python, it's more common to iterate over the values directly



          for value in lst:
          if value >= 0:
          total += value


          or use a list comprehension



          total = sum([x for x in lst if x >= 0])





          share|improve this answer


























          • my whole point was trying to work with a while loop. I know there are likely better methods to get to the end result. However, i wanted it to break the loop whenever it finds the 1st positive element, not negative. I believe it does that? Thanks.

            – JonnyChimpo
            10 hours ago











          • @edited. You need continue, not break

            – blue_note
            10 hours ago













          • continue doesn't work plus I don't understand why I'd use that... How do I break the loop without telling it to "break"?

            – JonnyChimpo
            10 hours ago











          • if you break the loop, you lose all negative values that follow. try list [1, -10, -10], it would give 0

            – blue_note
            9 hours ago











          • doesn't make sense. My code starts with -7 and adds up all negative numbers til it hits 1. Since 1 is positive, the loop breaks and the script ends. = -17. It works this way. Also, given your list it works as well as the result is -20..

            – JonnyChimpo
            9 hours ago





















          0














          To be honest this isn't the best way to write this, however if you have a sorted list where all the negative numbers are on one side than this will work.



          This issue is that you set i equal to 0, which would be 7 in that list. So what your while loop is doing is, 7 + -7 + -5 + -3 + -2... You will likely want to start i = -1 so that the first object it adds is -7 which will give you your desired results.



          # sum all the negative numbers using a while loop
          given_list3 = [7, 5, 4, 4, 3, 1, -2, -3, -5 ,-7]
          total6 = 0
          i = -1
          while -1 < 0:
          total6 += given_list3[i]
          i += -1
          if given_list3[i] > 0:
          break
          print(total6)


          To explain why this works you need to understand the positioning in a list or array. Given your list:



          List items:  [7, 5, 4, 4, 3, 1, -2, -3, -5 ,-7]
          Positions: [0][1][2][3][4][5] [6] [7] [8] [9]

          List items: [ 7, 5, 4, 4, 3, 1, -2, -3, -5 ,-7]
          From Reverse:[-10][-9][-8][-7][-6][-5][-4][-3][-2][-1]


          If you want to look at it you can see it this way as a continuous spectrum:



          List:     [   7,  5,  4,  4,  3,  1, -2, -3, -5 ,-7, 7, 5, 4, 4, 3, 1, -2, -3, -5 ,-7]
          Positions:[ -10][-9][-8][-7][-6][-5][-4][-3][-2][-1][0][1][2][3][4][5] [6] [7] [8] [9]


          While your list only contains 7,..-7, the call to "given_list3" operates on the above spectrum. Allowing negative numbers to work from the right while 0 and higher work from the left.






          share|improve this answer
























          • Thanks-- So when I set i = -1 does that mean the 1st object this loop looks at is going to be the last number in the list? Versus 0 = 1st number right?

            – JonnyChimpo
            11 hours ago











          • Just expanded on my answer here, that would be a correct statement.

            – Alexander Wryn
            11 hours ago











          • Interesting. So i just updated my code and made i = 9. That worked the same as when i did i = -1. I didn't realize i was writing it from a reverse angle. Logically, using i = 9 makes more sense to me. Thanks for the well thought out and clear response.

            – JonnyChimpo
            10 hours ago













          • Starting from the reverse isn't a bad idea, it's use case is if you have a sorted list of unknown length and you don't want to waste a line determining how long the list is. Otherwise you need to know the length of the list before you can run it.

            – Alexander Wryn
            10 hours ago













          • perfect. thanks.

            – JonnyChimpo
            10 hours ago



















          0














          If you'll have a List wherein the negative values are scattered it might be best to loop through every single object, compare if it's < 0 and then add it to your total.



          given_list = [-2,-3,5,7,4,-5,4,3,1,-7]
          total = 0
          for num in given_list:
          if num < 0:
          total = total + num
          print(total)


          In this case, you won't have to worry about starting on the other side of the list.






          share|improve this answer































            0














            You should put a debugger and step through each line that is executed. You will see that the first value added is the numbers[0], which is the positive number 7. From there on, it just works like you expect it to; it loops back and adds the numbers till it finds a positive number and then exits.





            You can use higher order functions like filter and sum to make your code more elegant and less error prone.



            numbers = [7, 5, 4, 4, 3, 1, -2, -3, -5 ,-7]

            sum(filter(lambda x: x<0, numbers))





            share|improve this answer


























            • i like the debugger idea so i can see what happens with each line. thnks for the response.

              – JonnyChimpo
              10 hours ago











            • That is our main tool :-)

              – Nishant
              10 hours ago











            • thnks. I've been using Jupyter to write code so i'll have to find the debugger option.

              – JonnyChimpo
              10 hours ago











            • You can do it using import pdb; pdb.set_trace.

              – Nishant
              10 hours ago












            Your Answer






            StackExchange.ifUsing("editor", function () {
            StackExchange.using("externalEditor", function () {
            StackExchange.using("snippets", function () {
            StackExchange.snippets.init();
            });
            });
            }, "code-snippets");

            StackExchange.ready(function() {
            var channelOptions = {
            tags: "".split(" "),
            id: "1"
            };
            initTagRenderer("".split(" "), "".split(" "), channelOptions);

            StackExchange.using("externalEditor", function() {
            // Have to fire editor after snippets, if snippets enabled
            if (StackExchange.settings.snippets.snippetsEnabled) {
            StackExchange.using("snippets", function() {
            createEditor();
            });
            }
            else {
            createEditor();
            }
            });

            function createEditor() {
            StackExchange.prepareEditor({
            heartbeatType: 'answer',
            autoActivateHeartbeat: false,
            convertImagesToLinks: true,
            noModals: true,
            showLowRepImageUploadWarning: true,
            reputationToPostImages: 10,
            bindNavPrevention: true,
            postfix: "",
            imageUploader: {
            brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
            contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
            allowUrls: true
            },
            onDemand: true,
            discardSelector: ".discard-answer"
            ,immediatelyShowMarkdownHelp:true
            });


            }
            });














            draft saved

            draft discarded


















            StackExchange.ready(
            function () {
            StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f55521937%2fpython-summing-neg-values-using-while-loop%23new-answer', 'question_page');
            }
            );

            Post as a guest















            Required, but never shown

























            4 Answers
            4






            active

            oldest

            votes








            4 Answers
            4






            active

            oldest

            votes









            active

            oldest

            votes






            active

            oldest

            votes









            1














            Various thing wrong




            • the -1 < 0 does not make sense, it wont terminate

            • you break when you find the first negative element


            You should do something like



            index = 0

            while index < len(lst):
            value = lst[index]

            if value > 0:
            continue

            total += value

            index += 1


            Note that, in python, it's more common to iterate over the values directly



            for value in lst:
            if value >= 0:
            total += value


            or use a list comprehension



            total = sum([x for x in lst if x >= 0])





            share|improve this answer


























            • my whole point was trying to work with a while loop. I know there are likely better methods to get to the end result. However, i wanted it to break the loop whenever it finds the 1st positive element, not negative. I believe it does that? Thanks.

              – JonnyChimpo
              10 hours ago











            • @edited. You need continue, not break

              – blue_note
              10 hours ago













            • continue doesn't work plus I don't understand why I'd use that... How do I break the loop without telling it to "break"?

              – JonnyChimpo
              10 hours ago











            • if you break the loop, you lose all negative values that follow. try list [1, -10, -10], it would give 0

              – blue_note
              9 hours ago











            • doesn't make sense. My code starts with -7 and adds up all negative numbers til it hits 1. Since 1 is positive, the loop breaks and the script ends. = -17. It works this way. Also, given your list it works as well as the result is -20..

              – JonnyChimpo
              9 hours ago


















            1














            Various thing wrong




            • the -1 < 0 does not make sense, it wont terminate

            • you break when you find the first negative element


            You should do something like



            index = 0

            while index < len(lst):
            value = lst[index]

            if value > 0:
            continue

            total += value

            index += 1


            Note that, in python, it's more common to iterate over the values directly



            for value in lst:
            if value >= 0:
            total += value


            or use a list comprehension



            total = sum([x for x in lst if x >= 0])





            share|improve this answer


























            • my whole point was trying to work with a while loop. I know there are likely better methods to get to the end result. However, i wanted it to break the loop whenever it finds the 1st positive element, not negative. I believe it does that? Thanks.

              – JonnyChimpo
              10 hours ago











            • @edited. You need continue, not break

              – blue_note
              10 hours ago













            • continue doesn't work plus I don't understand why I'd use that... How do I break the loop without telling it to "break"?

              – JonnyChimpo
              10 hours ago











            • if you break the loop, you lose all negative values that follow. try list [1, -10, -10], it would give 0

              – blue_note
              9 hours ago











            • doesn't make sense. My code starts with -7 and adds up all negative numbers til it hits 1. Since 1 is positive, the loop breaks and the script ends. = -17. It works this way. Also, given your list it works as well as the result is -20..

              – JonnyChimpo
              9 hours ago
















            1












            1








            1







            Various thing wrong




            • the -1 < 0 does not make sense, it wont terminate

            • you break when you find the first negative element


            You should do something like



            index = 0

            while index < len(lst):
            value = lst[index]

            if value > 0:
            continue

            total += value

            index += 1


            Note that, in python, it's more common to iterate over the values directly



            for value in lst:
            if value >= 0:
            total += value


            or use a list comprehension



            total = sum([x for x in lst if x >= 0])





            share|improve this answer















            Various thing wrong




            • the -1 < 0 does not make sense, it wont terminate

            • you break when you find the first negative element


            You should do something like



            index = 0

            while index < len(lst):
            value = lst[index]

            if value > 0:
            continue

            total += value

            index += 1


            Note that, in python, it's more common to iterate over the values directly



            for value in lst:
            if value >= 0:
            total += value


            or use a list comprehension



            total = sum([x for x in lst if x >= 0])






            share|improve this answer














            share|improve this answer



            share|improve this answer








            edited 10 hours ago

























            answered 10 hours ago









            blue_noteblue_note

            12.1k32536




            12.1k32536













            • my whole point was trying to work with a while loop. I know there are likely better methods to get to the end result. However, i wanted it to break the loop whenever it finds the 1st positive element, not negative. I believe it does that? Thanks.

              – JonnyChimpo
              10 hours ago











            • @edited. You need continue, not break

              – blue_note
              10 hours ago













            • continue doesn't work plus I don't understand why I'd use that... How do I break the loop without telling it to "break"?

              – JonnyChimpo
              10 hours ago











            • if you break the loop, you lose all negative values that follow. try list [1, -10, -10], it would give 0

              – blue_note
              9 hours ago











            • doesn't make sense. My code starts with -7 and adds up all negative numbers til it hits 1. Since 1 is positive, the loop breaks and the script ends. = -17. It works this way. Also, given your list it works as well as the result is -20..

              – JonnyChimpo
              9 hours ago





















            • my whole point was trying to work with a while loop. I know there are likely better methods to get to the end result. However, i wanted it to break the loop whenever it finds the 1st positive element, not negative. I believe it does that? Thanks.

              – JonnyChimpo
              10 hours ago











            • @edited. You need continue, not break

              – blue_note
              10 hours ago













            • continue doesn't work plus I don't understand why I'd use that... How do I break the loop without telling it to "break"?

              – JonnyChimpo
              10 hours ago











            • if you break the loop, you lose all negative values that follow. try list [1, -10, -10], it would give 0

              – blue_note
              9 hours ago











            • doesn't make sense. My code starts with -7 and adds up all negative numbers til it hits 1. Since 1 is positive, the loop breaks and the script ends. = -17. It works this way. Also, given your list it works as well as the result is -20..

              – JonnyChimpo
              9 hours ago



















            my whole point was trying to work with a while loop. I know there are likely better methods to get to the end result. However, i wanted it to break the loop whenever it finds the 1st positive element, not negative. I believe it does that? Thanks.

            – JonnyChimpo
            10 hours ago





            my whole point was trying to work with a while loop. I know there are likely better methods to get to the end result. However, i wanted it to break the loop whenever it finds the 1st positive element, not negative. I believe it does that? Thanks.

            – JonnyChimpo
            10 hours ago













            @edited. You need continue, not break

            – blue_note
            10 hours ago







            @edited. You need continue, not break

            – blue_note
            10 hours ago















            continue doesn't work plus I don't understand why I'd use that... How do I break the loop without telling it to "break"?

            – JonnyChimpo
            10 hours ago





            continue doesn't work plus I don't understand why I'd use that... How do I break the loop without telling it to "break"?

            – JonnyChimpo
            10 hours ago













            if you break the loop, you lose all negative values that follow. try list [1, -10, -10], it would give 0

            – blue_note
            9 hours ago





            if you break the loop, you lose all negative values that follow. try list [1, -10, -10], it would give 0

            – blue_note
            9 hours ago













            doesn't make sense. My code starts with -7 and adds up all negative numbers til it hits 1. Since 1 is positive, the loop breaks and the script ends. = -17. It works this way. Also, given your list it works as well as the result is -20..

            – JonnyChimpo
            9 hours ago







            doesn't make sense. My code starts with -7 and adds up all negative numbers til it hits 1. Since 1 is positive, the loop breaks and the script ends. = -17. It works this way. Also, given your list it works as well as the result is -20..

            – JonnyChimpo
            9 hours ago















            0














            To be honest this isn't the best way to write this, however if you have a sorted list where all the negative numbers are on one side than this will work.



            This issue is that you set i equal to 0, which would be 7 in that list. So what your while loop is doing is, 7 + -7 + -5 + -3 + -2... You will likely want to start i = -1 so that the first object it adds is -7 which will give you your desired results.



            # sum all the negative numbers using a while loop
            given_list3 = [7, 5, 4, 4, 3, 1, -2, -3, -5 ,-7]
            total6 = 0
            i = -1
            while -1 < 0:
            total6 += given_list3[i]
            i += -1
            if given_list3[i] > 0:
            break
            print(total6)


            To explain why this works you need to understand the positioning in a list or array. Given your list:



            List items:  [7, 5, 4, 4, 3, 1, -2, -3, -5 ,-7]
            Positions: [0][1][2][3][4][5] [6] [7] [8] [9]

            List items: [ 7, 5, 4, 4, 3, 1, -2, -3, -5 ,-7]
            From Reverse:[-10][-9][-8][-7][-6][-5][-4][-3][-2][-1]


            If you want to look at it you can see it this way as a continuous spectrum:



            List:     [   7,  5,  4,  4,  3,  1, -2, -3, -5 ,-7, 7, 5, 4, 4, 3, 1, -2, -3, -5 ,-7]
            Positions:[ -10][-9][-8][-7][-6][-5][-4][-3][-2][-1][0][1][2][3][4][5] [6] [7] [8] [9]


            While your list only contains 7,..-7, the call to "given_list3" operates on the above spectrum. Allowing negative numbers to work from the right while 0 and higher work from the left.






            share|improve this answer
























            • Thanks-- So when I set i = -1 does that mean the 1st object this loop looks at is going to be the last number in the list? Versus 0 = 1st number right?

              – JonnyChimpo
              11 hours ago











            • Just expanded on my answer here, that would be a correct statement.

              – Alexander Wryn
              11 hours ago











            • Interesting. So i just updated my code and made i = 9. That worked the same as when i did i = -1. I didn't realize i was writing it from a reverse angle. Logically, using i = 9 makes more sense to me. Thanks for the well thought out and clear response.

              – JonnyChimpo
              10 hours ago













            • Starting from the reverse isn't a bad idea, it's use case is if you have a sorted list of unknown length and you don't want to waste a line determining how long the list is. Otherwise you need to know the length of the list before you can run it.

              – Alexander Wryn
              10 hours ago













            • perfect. thanks.

              – JonnyChimpo
              10 hours ago
















            0














            To be honest this isn't the best way to write this, however if you have a sorted list where all the negative numbers are on one side than this will work.



            This issue is that you set i equal to 0, which would be 7 in that list. So what your while loop is doing is, 7 + -7 + -5 + -3 + -2... You will likely want to start i = -1 so that the first object it adds is -7 which will give you your desired results.



            # sum all the negative numbers using a while loop
            given_list3 = [7, 5, 4, 4, 3, 1, -2, -3, -5 ,-7]
            total6 = 0
            i = -1
            while -1 < 0:
            total6 += given_list3[i]
            i += -1
            if given_list3[i] > 0:
            break
            print(total6)


            To explain why this works you need to understand the positioning in a list or array. Given your list:



            List items:  [7, 5, 4, 4, 3, 1, -2, -3, -5 ,-7]
            Positions: [0][1][2][3][4][5] [6] [7] [8] [9]

            List items: [ 7, 5, 4, 4, 3, 1, -2, -3, -5 ,-7]
            From Reverse:[-10][-9][-8][-7][-6][-5][-4][-3][-2][-1]


            If you want to look at it you can see it this way as a continuous spectrum:



            List:     [   7,  5,  4,  4,  3,  1, -2, -3, -5 ,-7, 7, 5, 4, 4, 3, 1, -2, -3, -5 ,-7]
            Positions:[ -10][-9][-8][-7][-6][-5][-4][-3][-2][-1][0][1][2][3][4][5] [6] [7] [8] [9]


            While your list only contains 7,..-7, the call to "given_list3" operates on the above spectrum. Allowing negative numbers to work from the right while 0 and higher work from the left.






            share|improve this answer
























            • Thanks-- So when I set i = -1 does that mean the 1st object this loop looks at is going to be the last number in the list? Versus 0 = 1st number right?

              – JonnyChimpo
              11 hours ago











            • Just expanded on my answer here, that would be a correct statement.

              – Alexander Wryn
              11 hours ago











            • Interesting. So i just updated my code and made i = 9. That worked the same as when i did i = -1. I didn't realize i was writing it from a reverse angle. Logically, using i = 9 makes more sense to me. Thanks for the well thought out and clear response.

              – JonnyChimpo
              10 hours ago













            • Starting from the reverse isn't a bad idea, it's use case is if you have a sorted list of unknown length and you don't want to waste a line determining how long the list is. Otherwise you need to know the length of the list before you can run it.

              – Alexander Wryn
              10 hours ago













            • perfect. thanks.

              – JonnyChimpo
              10 hours ago














            0












            0








            0







            To be honest this isn't the best way to write this, however if you have a sorted list where all the negative numbers are on one side than this will work.



            This issue is that you set i equal to 0, which would be 7 in that list. So what your while loop is doing is, 7 + -7 + -5 + -3 + -2... You will likely want to start i = -1 so that the first object it adds is -7 which will give you your desired results.



            # sum all the negative numbers using a while loop
            given_list3 = [7, 5, 4, 4, 3, 1, -2, -3, -5 ,-7]
            total6 = 0
            i = -1
            while -1 < 0:
            total6 += given_list3[i]
            i += -1
            if given_list3[i] > 0:
            break
            print(total6)


            To explain why this works you need to understand the positioning in a list or array. Given your list:



            List items:  [7, 5, 4, 4, 3, 1, -2, -3, -5 ,-7]
            Positions: [0][1][2][3][4][5] [6] [7] [8] [9]

            List items: [ 7, 5, 4, 4, 3, 1, -2, -3, -5 ,-7]
            From Reverse:[-10][-9][-8][-7][-6][-5][-4][-3][-2][-1]


            If you want to look at it you can see it this way as a continuous spectrum:



            List:     [   7,  5,  4,  4,  3,  1, -2, -3, -5 ,-7, 7, 5, 4, 4, 3, 1, -2, -3, -5 ,-7]
            Positions:[ -10][-9][-8][-7][-6][-5][-4][-3][-2][-1][0][1][2][3][4][5] [6] [7] [8] [9]


            While your list only contains 7,..-7, the call to "given_list3" operates on the above spectrum. Allowing negative numbers to work from the right while 0 and higher work from the left.






            share|improve this answer













            To be honest this isn't the best way to write this, however if you have a sorted list where all the negative numbers are on one side than this will work.



            This issue is that you set i equal to 0, which would be 7 in that list. So what your while loop is doing is, 7 + -7 + -5 + -3 + -2... You will likely want to start i = -1 so that the first object it adds is -7 which will give you your desired results.



            # sum all the negative numbers using a while loop
            given_list3 = [7, 5, 4, 4, 3, 1, -2, -3, -5 ,-7]
            total6 = 0
            i = -1
            while -1 < 0:
            total6 += given_list3[i]
            i += -1
            if given_list3[i] > 0:
            break
            print(total6)


            To explain why this works you need to understand the positioning in a list or array. Given your list:



            List items:  [7, 5, 4, 4, 3, 1, -2, -3, -5 ,-7]
            Positions: [0][1][2][3][4][5] [6] [7] [8] [9]

            List items: [ 7, 5, 4, 4, 3, 1, -2, -3, -5 ,-7]
            From Reverse:[-10][-9][-8][-7][-6][-5][-4][-3][-2][-1]


            If you want to look at it you can see it this way as a continuous spectrum:



            List:     [   7,  5,  4,  4,  3,  1, -2, -3, -5 ,-7, 7, 5, 4, 4, 3, 1, -2, -3, -5 ,-7]
            Positions:[ -10][-9][-8][-7][-6][-5][-4][-3][-2][-1][0][1][2][3][4][5] [6] [7] [8] [9]


            While your list only contains 7,..-7, the call to "given_list3" operates on the above spectrum. Allowing negative numbers to work from the right while 0 and higher work from the left.







            share|improve this answer












            share|improve this answer



            share|improve this answer










            answered 11 hours ago









            Alexander WrynAlexander Wryn

            83




            83













            • Thanks-- So when I set i = -1 does that mean the 1st object this loop looks at is going to be the last number in the list? Versus 0 = 1st number right?

              – JonnyChimpo
              11 hours ago











            • Just expanded on my answer here, that would be a correct statement.

              – Alexander Wryn
              11 hours ago











            • Interesting. So i just updated my code and made i = 9. That worked the same as when i did i = -1. I didn't realize i was writing it from a reverse angle. Logically, using i = 9 makes more sense to me. Thanks for the well thought out and clear response.

              – JonnyChimpo
              10 hours ago













            • Starting from the reverse isn't a bad idea, it's use case is if you have a sorted list of unknown length and you don't want to waste a line determining how long the list is. Otherwise you need to know the length of the list before you can run it.

              – Alexander Wryn
              10 hours ago













            • perfect. thanks.

              – JonnyChimpo
              10 hours ago



















            • Thanks-- So when I set i = -1 does that mean the 1st object this loop looks at is going to be the last number in the list? Versus 0 = 1st number right?

              – JonnyChimpo
              11 hours ago











            • Just expanded on my answer here, that would be a correct statement.

              – Alexander Wryn
              11 hours ago











            • Interesting. So i just updated my code and made i = 9. That worked the same as when i did i = -1. I didn't realize i was writing it from a reverse angle. Logically, using i = 9 makes more sense to me. Thanks for the well thought out and clear response.

              – JonnyChimpo
              10 hours ago













            • Starting from the reverse isn't a bad idea, it's use case is if you have a sorted list of unknown length and you don't want to waste a line determining how long the list is. Otherwise you need to know the length of the list before you can run it.

              – Alexander Wryn
              10 hours ago













            • perfect. thanks.

              – JonnyChimpo
              10 hours ago

















            Thanks-- So when I set i = -1 does that mean the 1st object this loop looks at is going to be the last number in the list? Versus 0 = 1st number right?

            – JonnyChimpo
            11 hours ago





            Thanks-- So when I set i = -1 does that mean the 1st object this loop looks at is going to be the last number in the list? Versus 0 = 1st number right?

            – JonnyChimpo
            11 hours ago













            Just expanded on my answer here, that would be a correct statement.

            – Alexander Wryn
            11 hours ago





            Just expanded on my answer here, that would be a correct statement.

            – Alexander Wryn
            11 hours ago













            Interesting. So i just updated my code and made i = 9. That worked the same as when i did i = -1. I didn't realize i was writing it from a reverse angle. Logically, using i = 9 makes more sense to me. Thanks for the well thought out and clear response.

            – JonnyChimpo
            10 hours ago







            Interesting. So i just updated my code and made i = 9. That worked the same as when i did i = -1. I didn't realize i was writing it from a reverse angle. Logically, using i = 9 makes more sense to me. Thanks for the well thought out and clear response.

            – JonnyChimpo
            10 hours ago















            Starting from the reverse isn't a bad idea, it's use case is if you have a sorted list of unknown length and you don't want to waste a line determining how long the list is. Otherwise you need to know the length of the list before you can run it.

            – Alexander Wryn
            10 hours ago







            Starting from the reverse isn't a bad idea, it's use case is if you have a sorted list of unknown length and you don't want to waste a line determining how long the list is. Otherwise you need to know the length of the list before you can run it.

            – Alexander Wryn
            10 hours ago















            perfect. thanks.

            – JonnyChimpo
            10 hours ago





            perfect. thanks.

            – JonnyChimpo
            10 hours ago











            0














            If you'll have a List wherein the negative values are scattered it might be best to loop through every single object, compare if it's < 0 and then add it to your total.



            given_list = [-2,-3,5,7,4,-5,4,3,1,-7]
            total = 0
            for num in given_list:
            if num < 0:
            total = total + num
            print(total)


            In this case, you won't have to worry about starting on the other side of the list.






            share|improve this answer




























              0














              If you'll have a List wherein the negative values are scattered it might be best to loop through every single object, compare if it's < 0 and then add it to your total.



              given_list = [-2,-3,5,7,4,-5,4,3,1,-7]
              total = 0
              for num in given_list:
              if num < 0:
              total = total + num
              print(total)


              In this case, you won't have to worry about starting on the other side of the list.






              share|improve this answer


























                0












                0








                0







                If you'll have a List wherein the negative values are scattered it might be best to loop through every single object, compare if it's < 0 and then add it to your total.



                given_list = [-2,-3,5,7,4,-5,4,3,1,-7]
                total = 0
                for num in given_list:
                if num < 0:
                total = total + num
                print(total)


                In this case, you won't have to worry about starting on the other side of the list.






                share|improve this answer













                If you'll have a List wherein the negative values are scattered it might be best to loop through every single object, compare if it's < 0 and then add it to your total.



                given_list = [-2,-3,5,7,4,-5,4,3,1,-7]
                total = 0
                for num in given_list:
                if num < 0:
                total = total + num
                print(total)


                In this case, you won't have to worry about starting on the other side of the list.







                share|improve this answer












                share|improve this answer



                share|improve this answer










                answered 10 hours ago









                PaoloPaolo

                257112




                257112























                    0














                    You should put a debugger and step through each line that is executed. You will see that the first value added is the numbers[0], which is the positive number 7. From there on, it just works like you expect it to; it loops back and adds the numbers till it finds a positive number and then exits.





                    You can use higher order functions like filter and sum to make your code more elegant and less error prone.



                    numbers = [7, 5, 4, 4, 3, 1, -2, -3, -5 ,-7]

                    sum(filter(lambda x: x<0, numbers))





                    share|improve this answer


























                    • i like the debugger idea so i can see what happens with each line. thnks for the response.

                      – JonnyChimpo
                      10 hours ago











                    • That is our main tool :-)

                      – Nishant
                      10 hours ago











                    • thnks. I've been using Jupyter to write code so i'll have to find the debugger option.

                      – JonnyChimpo
                      10 hours ago











                    • You can do it using import pdb; pdb.set_trace.

                      – Nishant
                      10 hours ago
















                    0














                    You should put a debugger and step through each line that is executed. You will see that the first value added is the numbers[0], which is the positive number 7. From there on, it just works like you expect it to; it loops back and adds the numbers till it finds a positive number and then exits.





                    You can use higher order functions like filter and sum to make your code more elegant and less error prone.



                    numbers = [7, 5, 4, 4, 3, 1, -2, -3, -5 ,-7]

                    sum(filter(lambda x: x<0, numbers))





                    share|improve this answer


























                    • i like the debugger idea so i can see what happens with each line. thnks for the response.

                      – JonnyChimpo
                      10 hours ago











                    • That is our main tool :-)

                      – Nishant
                      10 hours ago











                    • thnks. I've been using Jupyter to write code so i'll have to find the debugger option.

                      – JonnyChimpo
                      10 hours ago











                    • You can do it using import pdb; pdb.set_trace.

                      – Nishant
                      10 hours ago














                    0












                    0








                    0







                    You should put a debugger and step through each line that is executed. You will see that the first value added is the numbers[0], which is the positive number 7. From there on, it just works like you expect it to; it loops back and adds the numbers till it finds a positive number and then exits.





                    You can use higher order functions like filter and sum to make your code more elegant and less error prone.



                    numbers = [7, 5, 4, 4, 3, 1, -2, -3, -5 ,-7]

                    sum(filter(lambda x: x<0, numbers))





                    share|improve this answer















                    You should put a debugger and step through each line that is executed. You will see that the first value added is the numbers[0], which is the positive number 7. From there on, it just works like you expect it to; it loops back and adds the numbers till it finds a positive number and then exits.





                    You can use higher order functions like filter and sum to make your code more elegant and less error prone.



                    numbers = [7, 5, 4, 4, 3, 1, -2, -3, -5 ,-7]

                    sum(filter(lambda x: x<0, numbers))






                    share|improve this answer














                    share|improve this answer



                    share|improve this answer








                    edited 10 hours ago

























                    answered 10 hours ago









                    NishantNishant

                    9,346124259




                    9,346124259













                    • i like the debugger idea so i can see what happens with each line. thnks for the response.

                      – JonnyChimpo
                      10 hours ago











                    • That is our main tool :-)

                      – Nishant
                      10 hours ago











                    • thnks. I've been using Jupyter to write code so i'll have to find the debugger option.

                      – JonnyChimpo
                      10 hours ago











                    • You can do it using import pdb; pdb.set_trace.

                      – Nishant
                      10 hours ago



















                    • i like the debugger idea so i can see what happens with each line. thnks for the response.

                      – JonnyChimpo
                      10 hours ago











                    • That is our main tool :-)

                      – Nishant
                      10 hours ago











                    • thnks. I've been using Jupyter to write code so i'll have to find the debugger option.

                      – JonnyChimpo
                      10 hours ago











                    • You can do it using import pdb; pdb.set_trace.

                      – Nishant
                      10 hours ago

















                    i like the debugger idea so i can see what happens with each line. thnks for the response.

                    – JonnyChimpo
                    10 hours ago





                    i like the debugger idea so i can see what happens with each line. thnks for the response.

                    – JonnyChimpo
                    10 hours ago













                    That is our main tool :-)

                    – Nishant
                    10 hours ago





                    That is our main tool :-)

                    – Nishant
                    10 hours ago













                    thnks. I've been using Jupyter to write code so i'll have to find the debugger option.

                    – JonnyChimpo
                    10 hours ago





                    thnks. I've been using Jupyter to write code so i'll have to find the debugger option.

                    – JonnyChimpo
                    10 hours ago













                    You can do it using import pdb; pdb.set_trace.

                    – Nishant
                    10 hours ago





                    You can do it using import pdb; pdb.set_trace.

                    – Nishant
                    10 hours ago


















                    draft saved

                    draft discarded




















































                    Thanks for contributing an answer to Stack Overflow!


                    • Please be sure to answer the question. Provide details and share your research!

                    But avoid



                    • Asking for help, clarification, or responding to other answers.

                    • Making statements based on opinion; back them up with references or personal experience.


                    To learn more, see our tips on writing great answers.




                    draft saved


                    draft discarded














                    StackExchange.ready(
                    function () {
                    StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f55521937%2fpython-summing-neg-values-using-while-loop%23new-answer', 'question_page');
                    }
                    );

                    Post as a guest















                    Required, but never shown





















































                    Required, but never shown














                    Required, but never shown












                    Required, but never shown







                    Required, but never shown

































                    Required, but never shown














                    Required, but never shown












                    Required, but never shown







                    Required, but never shown







                    Popular posts from this blog

                    VNC viewer RFB protocol error: bad desktop size 0x0I Cannot Type the Key 'd' (lowercase) in VNC Viewer...

                    Tribunal Administrativo e Fiscal de Mirandela Referências Menu de...

                    looking for continuous Screen Capture for retroactivly reproducing errors, timeback machineRolling desktop...