模仿python中的range功能

主要是利用生成器来写的一个函数:

def myxrange(start, stop = None, step = 1):     #这里的stop一定要等于None,不能等于0,要不然会有好多问题
    if stop == None:
        stop = start
        start = 0    
        while start < stop:
            yield start
            start += 1
    elif stop != None and step == 1:
        while start < stop:
            yield start
            start += 1
    else:
        if stop < start and step < 0:
            while start > stop:
                yield start
                start += step
        elif stop >= start and step > 0:
            while start < stop:
                yield start
                start += step
        else:
            print("不合法")
for x in myxrange(10, 0, -3):
    print(x,end = " ")
for x in myxrange(1, 10):
    print(x, end = " ")
for x in myxrange(10):
    print(x, end = " ")
print(sum(x**2 for x in myxrange(1, 10) if x % 2 != 0 ))

输出结果:

10 7 4 1

1 2 3 4 5 6 7 8 9

0 1 2 3 4 5 6 7 8 9

165

原文地址:https://www.cnblogs.com/zengsf/p/9514997.html