from operator import gt, lt def my_range_gen(start, stop=None, step=1): if stop is None: start, stop = 0, start if ( not step or start == stop or (step > 0 and start > stop) or (step < 0 and start < stop) ): return x, op = start, start > stop and gt or lt while op(x, stop): yield x x += step for i in my_range_gen(20, 10, 3): print(i) print("End")