Skip to main content
 首页 » 编程设计

python之while 遍历一个列表

2025年05月04日9cmt

我有一个数字列表,我想要这样,输入3个数字后,它们会相加,除非其中一个数字是13,否则其余数字将无效,不会相加。

因此,如果列表是 [1, 13, 2],则最终总和将为 1。

total = 0 
def lucky_sum(): 
    total = 0 
    lucky_sum = [] 
    a = input("Input a number") 
    b = input("Input a number") 
    c = input("Input a number") 
    lucky_sum.append(a) 
    lucky_sum.append(b) 
    lucky_sum.append(c) 
 
 
while **What do I place here??** != 13: 
    total += **and here** 
    if i== 13: 
        break 
print total 
 
lucky_sum() 

请您参考如下方法:

你可以不使用 while 循环来做到这一点:

for i in lucky_sum(): 
    if i == 13: 
        break 
 
    total += i 

编辑: 正如评论中所建议的,在 lucky_sum 末尾添加一个 return 语句。