Python 函数对偶数进行相加和求和
我编写这段代码是为了在字典中找到偶数值并输出总和。出于某种原因,我认为代码只获取字典中的第一个值。如果您有一点见解,我们将不胜感激:Python 函数对偶数进行相加和求和,python,loops,dictionary,Python,Loops,Dictionary,我编写这段代码是为了在字典中找到偶数值并输出总和。出于某种原因,我认为代码只获取字典中的第一个值。如果您有一点见解,我们将不胜感激: def sumEven(dct): total = 0 for val in dct.values(): if (val % 2 == 0): total += val return total user_dct = {'hero':6, 'b
def sumEven(dct):
total = 0
for val in dct.values():
if (val % 2 == 0):
total += val
return total
user_dct = {'hero':6,
'battlefields':4,
'villains':'everyone',
'outcome':1,
'possibilities':999}
sumEven(user_dct)
输出
10
提示:是否希望在for循环的第一次迭代中以偶数值返回?:D经过一个小时的反复检查!!它起作用了!!当您尝试测试“每个人”
是否为偶数时,您预计会发生什么情况?@MarkMeyer我希望代码避免任何不是int或float的内容,因此我正在测试该功能
def sumEven(dct):
total = 0
for val in dct.values():
if isinstance(val, int): #Filter out string
if (val % 2 == 0):
total += val
return total