Python基础语法整理【第三章-循环语句】

三、循环

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)

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

智慧化智能化数字化方案

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值