p007_get_even_numbers

代码:

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]

总结:

  1. result=[] 初始值写在for 循环上面;
  2. result.append(item),括弧及其里面的参数莫忘记;
  3. data=[item for item in range(begin,end) if item % 2==0]满足后面的条件再循环,然后添加到data列表中。
posted @ 2021-10-18 21:25  scholar-for-ever  阅读(30)  评论(0编辑  收藏  举报