法一:For循环
s = 0 for i in range(0, 101, 2): # range(start, stop, step) 不包括stop s += i print(s)
法二:while循环
s = 0 i = 0 while i < 101: if i % 2 == 0: s += i i += 1 print(s)
法三:先生成列表,再用sum()函数求和
print(sum(filter(lambda x: x % 2 == 0, range(100))))
或
print(sum(range(0, 101, 2))) # range()对象也可迭代
filter()函数:filter() 是通过生成 True 和 False 组成的迭代器将可迭代对象中不符合条件的元素过滤掉;而 map() 返回的则是 True 和 False 组成的迭代器。
filter(function, iterable) 返回值为iterable经过过滤后的列表
sum()函数:sum(iterable)
判断一个对象是否可迭代:hasattr(object, ''__iter__")
lambda表达式:
i = lambda a, b: a + b
print(i(1, 4))
结果为5
