题目:
输入开始和结束值(不包含),得到所有偶数
偶数:能够被2所整除的整数,是2的倍数。
输入:begin=3;end=20
返回:[4, 6, 8, 10, 12, 14, 16, 18]
解题思路:
1、创建一个空列表
2、用for循环遍历开始和结束值。
3、设定添加方法。
答案:
- 方法一:for循环
def numbers(begin,end):
result = []
for i in range(begin,end):
if i %2 == 0:
result.append(i)
return result
begin = 3
end = 20
print(f"begin={begin}, end={end},result numbers:",numbers(begin,end))
---------------------------------------
begin=3, end=20,result numbers: [4, 6, 8, 10, 12, 14, 16, 18]
- 方法二:推导式
begin = 3
end = 20
list1 = [i for i in range(begin,end) if i %2==0 ]
print(f"begin={begin}, end={end},result numbers:",list1)
--------------------------------------
begin=3, end=20,result numbers: [4, 6, 8, 10, 12, 14, 16, 18]
标签:begin,end,14,numbers,偶数,result,20,数字 From: https://www.cnblogs.com/LoLong/p/16837745.html