1、遍历整个列表
需要对列表中的每个元素都执行相同的操作时,可使用for循环
>>> colors
['green', 'orange', 'yellow', 'red']
>>> for color in colors:
print(color)
green
orange
yellow
red
python先获取colors的第一个值‘green’,并储存到变量color中。
接下来打印color
python返回到循环的第一行
python获取列表下一个名字‘orange’,并储存到变量color中
然后继续打印
对于列表每个元素,都执行循环指定的步骤,且不管列表包含多少个元素对于编写for程序的时候,对于用于储存你列表中每个值的变量,可指定任意名称。选择描述单个列表元素的有意义的名称大有帮助。比如cat-cats,dog-dogs,color-colors
2、for循环
colors = ['red','orange','yellow','green']
for color in colors:
print("I like "+color+"!")
print("But i cannot like " +color+" all the time!\n")
print("Thank you")
运行结果:
I like red!
But i cannot like red all the time!
I like orange!
But i cannot like orange all the time!
I like yellow!
But i cannot like yellow all the time!
I like green!
But i cannot like green all the time!
Thank you
前两条print语句缩进会重复执行,第三条print语句没有缩进,因此只执行一次。
3、创建数字列表
range()函数
python从指定的第一个值开始到指定的倒数第二个值停止。
举个栗子:
for value in range(1,5):
print(value)
1
2
3
4
for value in range(1,6):
1