given_list3 = [7, 5, 4, 4, 3, 1, -2, -3, -5, -7]
total3 = 0
i = 0
while given_list3[i] < 0:
total3 += given_list3[i]
i += 1
print(total3)
my goal is to only print the sum of the negative numbers in the list, but when I print the answer, it always says its 0, can anyone please help me?
I’ve edited your post for readability. When you enter a code block into the forum, precede it with a line of three backticks and follow it with a line of three backticks to make easier to read. See this post to find the backtick on your keyboard. The “preformatted text” tool in the editor (</>
) will also add backticks around text.
I think it’s because the condition for your while
isn’t actually doing what you want (looping through each number in the array).
The first time the while
loop is executed, given_list3[i]
has a value of 7
and therefore the condition given_list3[i] < 0
evaluates to false
. At this point the while
loop terminates and none of the code inside the while block is will be executed; hence the output is always 0
.
You could either restructure your while
loop by getting the relevant value in the list in the while
loop’s block:
while i < 0:
num = given_list3[i]
# Implement the rest of the logic for summing here
i += 1
Or, if I’m not mistaken, I think a for
loop would be more appropriate in this case:
for num in given_list[3]:
# Implement the rest of the logic for summing here
I hope that helps!
1 Like
Agree that a for loop would work better or at least more readable for this situation, but you can still make it work with a while loop, here is one way with the least change to your code
given_list3 = [7, 5, 4, 4, 3, 1, -2, -3, -5, -7]
total3 = 0
i = 0
while True:#entry condition: start infinte loop
if given_list3[i]<0:
total3 += given_list3[i]
i += 1
if i==len(given_list3):#exit condition: break loop when end of list is reached
break
print(total3)
The key is in knowing how to set the condition of starting the loop and another condition on how to end it. Try exploring other ways to achieve this as well.
If you understand the above then you can combine both the entry and exit conditions of the while loop like:
given_list3 = [7, 5, 4, 4, 3, 1, -2, -3, -5, -7]
total3 = 0
i = 0
while (i<len(given_list3)):#entry and exit condition combined
if given_list3[i]<0:
total3 += given_list3[i]
i += 1
print(total3)
1 Like
Hey Christian, do you absolutely need to use while loop? If not just use simple iteration addition`
given_list3 = [7, 5, 4, 4, 3, 1, -2, -3, -5, -7]
total3 = 0
for n in given_list3:
if n < 0:
total3 += n
print(total3)
[1]: -17
I hope this helps!