天天看点

python中loop是什么语句_Python,loop语句(for loop),循环,For

Python,循环语句(For循环)

For循环:

1.for循环可以遍历任何序列的项目,如一个列表或者一个字符串。

fruits = ['banana', 'apple',  'mango']

for fruit in fruits:

print ('当前水果 :', fruit)

打印结果:

当前水果 : banana

当前水果 : apple

当前水果 : mango

2.通过索引遍历

使用了内置函数 len() 和 range(),函数 len() 返回列表的长度,即元素的个数。 range返回一个序列的数。

fruits = ['banana', 'apple',  'mango']

for iin range(len(fruits)):

print ('当前水果 :', fruits[i])

打印结果:

当前水果 : banana

当前水果 : apple

当前水果 : mango

for i in range ()作用:

range()是一个函数, for i in range () 就是给i赋值:

比如 for i in range (1,3):

就是把1,2依次赋值给i

range () 函数的使用是这样的:

range(3)即:从0到3,不包含3,即0.1,2

range(1,3) 即:从1到3,不包含3,即1,2

range(1,3,2)即:1。第三个数字2是代表步长。如果不设置,就是默认步长为1

For i in range(100)

即:0-99,共100个