代码:
def get_even_numbers(i,j): result=[] for item in range(i,j): if item % 2==0: result.append(item) return result begin=4 end=15 data=[item for item in range(begin,end) if item % 2==0] print(f"begin={begin},end={end},even numbers: " ,data) print(f"begin={begin},end={end},even numbers: " ,get_even_numbers(begin,end))
效果:
begin=4,end=15,even numbers: [4, 6, 8, 10, 12, 14] begin=4,end=15,even numbers: [4, 6, 8, 10, 12, 14]
总结:
- result=[] 初始值写在for 循环上面;
- result.append(item),括弧及其里面的参数莫忘记;
- data=[item for item in range(begin,end) if item % 2==0]满足后面的条件再循环,然后添加到data列表中。