Home > front end >  can someone explain why the second code works but not the first?
can someone explain why the second code works but not the first?

Time:05-10

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

I am trying to add all the negative numbers together. The code above gives the answer 0.The code below gives the answer -17 (the correct answer). Why do they give different answers? To me it looks like both of them are the same, just written differently. I am clearly misunderstanding something. Can someone help me wrap my head around this?

given_list = [7,5,4,4,3,1,-2,-3,-5,-7]
total1 = 0
i = 0
while i < len(given_list):
    if given_list[i] < 0:
        total1  = given_list[i]
    i  = 1
print(total1)

CodePudding user response:

It's because the while loop first condition (while given_list[i] < 0) is false for the first element itself (7) and the loop doesn't execute itself. You can try printing the current looped element for more clarity

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

You can also try the above code minus the given_list[i] < 0 and print each looped item.

CodePudding user response:

The first while breaks at the first element of the list, because the condition evaluates to false. This happens because given_list[i] < 0 at Index 0, the value is greater than 0.

CodePudding user response:

It's because of the given_list[i] < 0. Your array will not pass this condition and not enter the loop. This will only pass if you negative numbers are first and then the others.

CodePudding user response:

The first program doesn't work because a while loop breaks when it's condition is false. So as soon as the loop enounters a positive number in the list, given_list[i] < 0 becomes false and the loop breaks.

What you want is to go through the whole list and check each element whether it is positive or not without breaking the loop.

  • Related