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列表中。
上一篇:【21天精听打卡 1/21】20211109 TED How daylight saving time affects our bodies,mind and world


下一篇:Codeforces Problem-318A Even Odds