在我的程序中,我需要放置一个while函数,该函数对该列表求和,直到找到一个特定的数字:
[5,8,1,999,7,5]
输出应该为14,因为它的总和为5 + 8 + 1,并在找到999时停止。
我的想法如下:
def mentre(llista):
while llista != 999:
solution = sum(llista)
return solution
最佳答案
明确使用while循环的示例如下:
def sum_until_found(lst, num):
index = 0
res = 0
if num in lst:
while index < lst.index(num):
res += lst[index]
index += 1
else:
return "The number is not in the list!"
return res
另一种可能的方式是:
def sum_until_found(lst, num):
index = 0
res = 0
found = False
if num in lst:
while not found:
res += lst[index]
index += 1
if lst[index] == num:
found = True
else:
return "The number is not in the list!"
return res
有许多不使用while循环的方法,其中一种是使用递归:
def sum_until_found_3(lst, num, res=0):
if num in lst:
if lst[0] == num:
return res
else:
return sum_until_found_3(lst[1:], num, res + lst[0])
else:
return "The number is not in the list!"
最后,一个更简单的解决方案:
def sum_until_found(lst, num):
if num in lst:
return sum(lst[:lst.index(num)])
else:
return "The number is not in the list!"