今天给大家讲述Python的循环语句第二小节.
上一节我们讲的while循环,这节我们讲For循环,对于了解计算机语言的童鞋们来说应该都很熟悉吧。
For循环可以遍历任何序列的项目,如一个列表或者一个字符串。(遍历:说白了就是把序列里面的第一个元素到最后一个元素挨个访问一次)
For循环语句的语法如下:
for 元素 in 序列的项目: 语句块
语句块:就是我们需要在循环体内要执行的代码。
引用网上的流程图:

图片来自网络,归作者所有
我们用一个例子来说明下:
list = [1, 2, 3, 4, 5] for item in list: print(item) 输出结果: 1 2 3 4
python有个有趣的地方,
在for循环后面可以使用else语句
for i in range(0,10):
if i > 5:
print(i)
else:
print("hello world")
输出结果:
6
7
8
9
hello world
切记else对齐代码否则就会像这样:
for i in range(0,10):
if i > 5:
print(i)
else:
print("hello world")
输出结果:
hello world
hello world
hello world
hello world
hello world
hello world
6
7
8
9
如果大家有什么不明白的可以加QQ群:983180497
