为什么我的 while 循环不对所有值求和

DL_*_*hon 1 python while-loop

我正在学习 Python 并且在理解 While 循环时遇到了一些麻烦。我试图计算负数的总数,但无法正确计算。

given_list3=[7,5,4,4,3,1,-2,-3,-5,-7]
total6=0
i=0
while i<len(given_list3)and given_list3[i]<0:
    total6+=given_list3[i]
    i+=1
print(total6)
Run Code Online (Sandbox Code Playgroud)

这是我计算正数总和的代码(工作正常)

given_list=[5,4,4,3,1,-3,-4,-5]
total3=0
i=0
while i<len(given_list) and given_list[i]>0:
    total3+= given_list[i]
    i+=1
print(total3)
Run Code Online (Sandbox Code Playgroud)

Nic*_*ick 5

你的问题是,当你计算负数的总和时,你的while循环在第一个值上退出,因为它没有通过given_list3[i]<0(你的正数总和起作用的唯一原因是正数都在列表的开头)。您应该将该检查移动到您的循环中,例如:

while i<len(given_list3):
    if given_list3[i]<0:
        total6+=given_list3[i]
    i+=1

print(total6)
Run Code Online (Sandbox Code Playgroud)

输出

-17
Run Code Online (Sandbox Code Playgroud)

请注意,您可以使用列表理解替换这样的简单循环,例如

total6 = sum([x for x in given_list3 if x < 0])
print(total6)
Run Code Online (Sandbox Code Playgroud)

输出

-17
Run Code Online (Sandbox Code Playgroud)