模仿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
【推荐】还在用 ECharts 开发大屏?试试这款永久免费的开源 BI 工具!
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步