pythonnegative-integer

in Python, I get a wrong total, i only get the total of the positive numbers that are located before the negative ones


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^^


Solution

  • 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.