given_list5=[7, 5, 4, 4, 3, 1, -2, -3, -5, -7]
total7=0
i = 0
while True:
if given_list5[i] >=0:
break
total7 += given_list5[i]
i += 1
print(total7)
This is my code. Please fix it for me. Thanks.
given_list5=[7, 5, 4, 4, 3, 1, -2, -3, -5, -7]
total_neg=0
for i in given_list5: #that means you select every item in the list by one by. it's a loop
if i<0:
total_neg+=i #that means total_neg=total_neg + i
print(total_neg)
Python allows single-line for loop convention. Also, for something like this, you can simply do:
given_list5 = [7, 5, 4, 4, 3, 1, -2, -3, -5, -7]
filtered_list5 = [i for i in given_list5 if i < 0]
total7 = sum(filtered_list5)
print(total7)
>> -17
Explanation: filtered_list5
filters the list of only negative numbers, and sum()
computes sum of all the elements in a list.
Combining everything in a single line: total7 = sum([i for i in given_list5 if i < 0])
EDIT Looking at the code-style by OP, as mentioned by @Nick, here is an implementation using:
a) for-loop
given_list5 = [7, 5, 4, 4, 3, 1, -2, -3, -5, -7]
total7 = 0
for number in given_list5:
if number < 0:
total7 += number
print(total7)
>> -17
b) while-loop
is actually tricky, if you are a beginner. To loop a list using while loop, you will have to use an inbuilt function .pop()
on the list. You can check check this explanation. So, on your code, the implementation would be:
given_list5 = [7, 5, 4, 4, 3, 1, -2, -3, -5, -7]
total7 = 0
while given_list5:
number = given_list5.pop()
if number < 0:
total7 += number
print(total7)
>> -17
for num in given_list5
: loop given_list5 elements
str.isdigit()
(check for numbers) : True = str, False : numeric
given_list5=[7, 5, 4, 4, 3, 1, -2, -3, -5, -7]
sumNegativeQuantity = 0
for num in given_list5 :
if (str(num).isdigit() == False) and (num < 0) :
sumNegativeQuantity += num
print(sumNegativeQuantity)
result
-17