老王学python2 的第7天---循环语句

1、python 里没有 do…while循环

2、while循环: 条件为true时会一直循环体,否则跳出循环

① 简单while循环

a = 1
while a < 10:
    a += 1
    print a

② 无限while循环

a = 1
while a != 1:
    print 'a等于1'

③ while 中使用else循环

a = 1
while a > 1:
    print 'a大于1'
else:
    print 'a不大于1'

3、for循环: 重复循环体

① 简单for语句

list = [1, 2, 'a', 'aa']
for value in list:
    print value

② 通过序列索引迭代

list = [1, 2, 'a', 'aa']
for index in range(len(list)):
    print index
    print list[index]

③ for循环中使用else

list = [
    [1, 3, 5, 7],
    [2, 4, 6, 8]
]
for item in list:
    for value in item:
        if(value % 2 == 0):
            print '偶数'
        else:
            print '奇数'

4、嵌套循环: while循环和for循环可以互相嵌套

① for循环嵌套 while

a = 1
for a in range(1, 20):
    a += 1
    while a > 10:
        print 'a 大于 10'
    else:
        print 'a 小于 10'

② for循环中嵌套 for循环

list = [
    [1, 3, 5, 7],
    [2, 4, 6, 8]
]
for item in list:
    for value in item:
        if(value % 2 == 0):
            print '偶数'
        else:
            print '奇数'

③ while循环中嵌套 for循环

while True:
    for value in [1, 2,3]:
        print value

④ while循环中嵌套 while循环

while True:
    while True:
        print 'True'

5、循环的控制语句

① break: 中止循环,跳出整个循环体

for value in 'addsdad':
    if value == 's':
        break
    print value # a  d  d

② continue:跳过本次循环,进行下一循环

for value in 'addsdad':
    if value == 's':
        continue
    print value # a  d  d  d  a  d

③ pass: 空语句,不做任何事,为了保持程序结构的完整性

for value in 'addsdad':
    if value == 's':
        pass
    print value # a  d  d  s  d  a  d

6、思维导图式总结(可以直接看这里)

在这里插入图片描述
在这里插入图片描述
在这里插入图片描述
在这里插入图片描述

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值