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^^
Try to understand the working of while loop. It works as long as
i < len(list
andlist[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
For your while loop code, use
Also, although you can use a variable name as
list
, it is advised not to do so in Python aslist
is also a keyword.