Python学习之路0x06
这一章我们介绍Python的循环语句
循环语句就是能让代码重复执行的语句,比如输出“Hello,world!”100次,如果没有循环语句,那么就需要写100句print,有了循环语句后,这样重复性的工作就变得容易了许多。
下面我们用小例子演示Python中的循环语句
#我们先看一下while循环,while循环在条件为True时执行,并不需要知道初始值为多少,只要给定判断条件,那么满足条件的while就会执行。
while 条件:
代码块
i = 0
while i<20:
print(i)
i += 1
#输出如下
0
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
#然后我们介绍一下for循环,Python中的for循环与c有所不同。Python中的for类似于for each循环,格式如下
for 变量 in 可迭代对象:
代码块
#下面看几个小例子
for item in range(10):
print(item,end=',')
0,1,2,3,4,5,6,7,8,9,
l = [4,5,6,7,8]
for item in l:
print(item,end=',')
4,5,6,7,8,
s = 'Hello,world'
for item in s:
print(item,end=' ')
H e l l o , w o r l d