函数原型:range(start, end, scan):
参数含义:start:计数从start开始。默认是从0开始。例如range(5)等价于range(0, 5);
end:技术到end结束,但不包括end.例如:range(0, 5) 是[0, 1, 2, 3, 4]没有5
scan:每次跳跃的间距,默认为1。例如:range(0, 5) 等价于 range(0, 5, 1)
range的类型:Python 2.x
range()
produced a list, and
xrange()
returned an iterator - a sequence object. in Python 3.x, the
range()
function got its own
type
.
有趣的用法: 倒序 for
i
in
range
(
99
,
0
,
-
1
)
:
浮点数的range:
>>> # Note: All arguments are required. >>> # We're not fancy enough to implement all. >>> def frange(start, stop, step): ... i = start ... while i < stop: ... yield i ... i += step ... >>> for i in frange(0.5, 1.0, 0.1): ... print(i) ... 0.5 0.6 0.7 0.8 0.9 1.0
求最大公约数,最小公倍数: (5-15.py)
def maxpub(a,b): a = int(a) b = int(b) if a>=b: small = b large = a else: small = a large = b pub = 1 #should include small in range #range(2,small+1) for i in range(2,small+1): i = i if (small%i==0 and large%i == 0): pub = pub * i small = small/i large = large/i continue else: i = i + 1 return pub def smallpub(a,b): a = int(a) b = int(b) return a*b/maxpub(a,b)