Python输出n以内的奇数或偶数

  • Post author:
  • Post category:python


方法1:
#参数k表示从多少开始,如k=0表示输出n以内的偶数,k=1表示输出n以内的奇数
def generateList(k,n):
    L=[]
    while(k<n):
        L.append(k)
        k=k+2
    print (L)

generateList(0,100)  #[0, 2, 4, 6, 8, 10...98]
generateList(1,100) #[1, 3, 5, 7, 9, 11...99]

方法2:

print(list(range(1,50,2)))  #输出50以内的奇数

[1, 3, 5, 7, 9, 11, 13, 15, 17, 19, 21, 23, 25, 27, 29, 31, 33, 35, 37, 39, 41, 43, 45, 47, 49]

print(list(range(0,50,2))) #输出50以内的偶数

[0, 2, 4, 6, 8, 10, 12, 14, 16, 18, 20, 22, 24, 26, 28, 30, 32, 34, 36, 38, 40, 42, 44, 46, 48]

print([i for i in range(0,40,2)])

[0, 2, 4, 6, 8, 10, 12, 14, 16, 18, 20, 22, 24, 26, 28, 30, 32, 34, 36, 38]

封装为函数:

def fk(k,n):
    print(list(range(k, n, 2)))
fk(1,50)  #[1, 3, 5, 7, 9, 11, 13, 15, 17, 19, 21, 23, 25, 27, 29, 31, 33, 35, 37, 39, 41, 43, 45, 47, 49]
fk(0,40)  #[0, 2, 4, 6, 8, 10, 12, 14, 16, 18, 20, 22, 24, 26, 28, 30, 32, 34, 36, 38]



版权声明:本文为qq_27437967原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。