三、循环
for循环
for循环的基本格式是:for…in…
#遍历字符串
>>>for i in 'coding':
... print(i)
c
o
d
i
n
g
#遍历列表
>>>for i in ['for','change']
... print(i)
for
change
for…in dict:
#遍历字典的键
>>>list = {1:'a',2:'b',3:'c'}
>>>for i in list:
... print(i)
1
2
3
for…in dict.values():
#遍历字典的值
>>>list = {1:'a',2:'b',3:'c'}
>>>for i in list.values():
... print(i)
a
b
c
for…in dict.items():
#遍历字典的键值对
>>>list = {1:'a',2:'b',3:'c'}
>>>for k, v in list.items():
... print(k)
... print(v)
1
a
2
b
3
c
range()函数
#range()有最基本的三种用法:range(b), range(a,b),range(a,b,c)。
#函数中各个数值的意义:a:计数从a开始。不填时,从0开始;b:计数到b结束,但不包括b;c:计数的间隔,不填时默认为1。
>>>range(5)
#计数依次为0,1,2,3,4
>>>range(1,5)
#计数依次为1,2,3,4
>>>range(2,8,2)
#计数依次为2,4,6
for…in range()
#处理指定次数的循环
>>>for i in range(3):
... print('第%d遍FB编程' %i)
第0遍FB编程
第1遍FB编程
第2遍FB编程
while循环
while循环
#当条件为真时,执行循环语句,只要条件为真,便会一直循环
>>>count = 3
>>>while count > 1:
... print('happy coding')
... count = count -1
happy coding
happy coding
while循环和for循环的区别:
#for擅长处理固定次,自动遍历各序列
#while处理不定次数的循环,条件为False便停止
循环进阶
break
#如果满足条件,则结束循环
>>>while True:
... print('happy coding')
... break
happy coding
#break会结束循环,如果只有前两行代码,会无限循环打印happy coding
>>>count = 3
>>>while count >1:
... print('happy coding')
... count = count - 1
... if count == 2: #当count等于2的时候,停止循环
... break
happy coding
#对比while循环的例子,我们发现这里只打印了一次happy coding
continue
#如果满足条件,则跳过当前循环的剩余语句,直接开始下一轮循环
count = 3
while count >1:
print('happy')
count = count - 1
if count == 2: #当count等于2的时候,跳过下列语句,重新开始新的一轮循环
continue
print('coding') #由于continue语句,coding只会打印一次
#打印的结果为:
happy
happy
coding
else
#无论是否进入循环,最后都会执行esle语句,除非执行break语句跳出循环
count = 3
while count >2:
print('在FB')
count = count -1
else: #无论是否进入循环都会执行else语句
print('happy coding')
#打印结果为:
在FB
happy coding
循环嵌套
#即循环中有循环
>>>for i in ['FB','编程']: #首先遍历列表元素
... for t in i: #然后遍历元素(字符串)
... print(t)