range () function
In other languages, if you want to loop a variable from 1-100, how to write it?
for(i = 1,i<=100,i++){}
python how to achieve this function? python design range () function, directly implements the above functions. range is a built-in function without import. Anywhere you can use it directly.
for i in range(5):
print(i)
0
1
2
3
4
从上面的执行结果,也可以看出来range函数的范围是从0-4。遵守左闭右开的原则。range默认是从0开始的。当然也可以指定遍历的区间。
for i in range(1,5):
print(i)
1
2
3
4
还可以指定步长,就像切片一样。
for i in range(1, 12, 2):
print(i)
1
3
5
7
9
11
很多的时候是结合range()和len()函数,遍历一个序列的索引
a = ['Google', 'Baidu', 'Huawei', 'Taobao', 'QQ']
for i in range(len(a)):
print(i, a[i])