i wrote this code in python:

list=[3,5,7,6,-9,5,4]
i=0
total=0
while i<len(list) and list[i] > 0:
     total+=list[i]
     i+=1
print(total)

and instead of getting the total of all positive numbers i only get the total of numbers that are located before the negative one, i'm not sure what i'm doing wrong, this is just my fourth code in python i'd like some help^^

3

There are 3 answers

0
Swati Srivastava On BEST ANSWER

Try to understand the working of while loop. It works as long as i < len(list and list[i] > 0. When it reaches the value -9, the while loop's second condition gets false and it terminates. Hence no sum is calculated after first negative integer is encountered.

To solve this, do

lis = [3, 5, 7, 6, -9, 5, 4]
sum = 0
for i in lis:
    if i > 0:
        sum += i

For your while loop code, use

lis = [3, 5, 7, 6, -9, 5, 4]
i = 0
sum = 0
while i < len(lis):
    if lis[i] > 0:
        sum += lis[i]
    i = i + 1

Also, although you can use a variable name as list, it is advised not to do so in Python as list is also a keyword.

1
Vincent Ramdhanie On

That is because you have the condition that the loop ends if you encounter a negative number. You can first remove that condition from the loop.

while i<len(list):

Next, you only want to add non-negative numbers so, use a conditional statement in the loop with the condition that you want.

if list[i] > 0:
0
Mark Tolonen On

Do not use a while loop in this case. Iteration over items in a container is easier in Python with a for loop. Plus the logic is wrong and exits the while loop early when it fails the and list[i] > 0 condition.

lst = [3,5,7,6,-9,5,4]
total = 0
for item in lst:
    if item > 0:
        total += item
print(total)

Also, don't use list as a variable name. That replaces the built-in list type and is called "shadowing".

You can also use a list comprehension and simplify the code even more:

lst = [3,5,7,6,-9,5,4]
total = sum([item for item in lst if item > 0])
print(total)