python实现range函数
用python的代码实现range相关的功能.1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
#!/usr/bin/env python
def r(start,end=None,step=1):
if step>0:
if not end:
start, end = 0, start
check = lambda x,y:x<y
elif step<0:
check = lambda x,y:x>y
else:
raise ValueError("range() step argument must not be zero")
tmp = []
while check(start, end):
tmp.append(start)
start+=step
return tmp
print r(2,6)
print r(1,10,2)
print r(10,-9,-4)
print r(-10)
print r(1,10,0)
结果:
1
2
3
4
5
6
7
8
9
10
11
$ python ran.py
[]
Traceback (most recent call last):
File "ran.py", line 25, in <module>
print r(1,10,0)
File "ran.py", line 13, in r
raise ValueError("range() step argument must not be zero")
ValueError: range() step argument must not be zero
页:
[1]