当满足条件时停止for循环或while循环



我是编程新手。目标是按顺序计数list中的数字,但是当满足或接近条件时,循环必须停止,但不能超过条件。

例如:list = [4,4,4,3,3],条件= 11预期输出将是4+4=8,因为另一个4将超出条件(4+4+4=12)。

list = [4,4,4,3,3]
condition = 11
def for_fun(list, condition):
sum_of_sizes = 0
for i in list:
sum_of_sizes += i
if sum_of_sizes <= condition:
break
return sum_of_sizes

我发现for循环更容易工作,尽管while循环可能更适合这项任务。

while添加到@matle的解中:

list = [4,4,4,3,3]
condition = 11
def for_fun(list, condition):
sum_of_sizes = 0
index = 0
while True:
if sum_of_sizes + list[index] > condition:
break
sum_of_sizes += list[index]
index += 1
return sum_of_sizes

print(for_fun(list, condition))

请尽量避免覆盖python关键字,如list!

我建议您检查您的下一个sum_of_sizes是否大于或等于您的条件,如果是这种情况,则中断。如果没有,就继续从列表中添加项目。此外,list是一个内置函数,所以请将list命名为其他函数,如input_list:

input_list = [4,4,4,3,3]
condition = 11
def for_fun(input_list, condition):
"""A function that adds up numbers and breaks if the next iteration would exceed condition"""

# initial sum of numbers
sum_of_sizes = 0

# iterate over your input list
for i in input_list:
# if the next sum of numbers would exceed condition, break
if sum_of_sizes+i > condition:
break
# add up numbers
sum_of_sizes += i
# return the sum at the end
return sum_of_sizes
# call and print your function, hand over your variables input_list and condition
print(for_fun(input_list=input_list, condition=condition))

相关内容

  • 没有找到相关文章

最新更新