Python 循环控制

    for循环
        Python for循环可以遍历任何序列的项目,如一个列表或者一个字符串
        for 变量 in 列表、字典、字符串、函数:
            执行语句
        例子1(列表、字典、字符串、函数)

#coding=utf-8
for i in 'heygor':
    print(i)
 
li=['heygor',250]
for i in li:
    print(i)
 
#range函数(范围)
for i in range(8):
    print(i)

for i in range(1,101):
    print(i)


    while循环
        while 后面判断条件只能是真或者假,如果为真,继续执行,如果为假,不执行
        while <condition>:
                <statesments>

#coding=utf-8
# a=6
# while a<10:
#     print(a)
#     a+=1    #a=a+1

# while True:
#     print('你真帅')

while 1:
    print('你真帅')

    Python会循环执行<statesments>,直到<condition>不满足为止。

    continue 语句
    遇到 continue 的时候,程序会返回到循环的最开始重新执行。

    例如在循环中忽略一些特定的值:

values = [7, 6, 4, 7, 19, 2, 1]
for i in values:
    if i % 2 != 0:
        # 忽略奇数
        continue
    print i/2
"""
3
2
1
"""


    break 语句
    遇到 break 的时候,程序会跳出循环,不管循环条件是不是满足:

command_list = ['start',
                'process',
                'process',
                'process',
                'stop',
                'start',
                'process',
                'stop']
while command_list:
    command = command_list.pop(0)
    if command == 'stop':
        break
    print(command)

start
process
process
process


    在遇到第一个 'stop' 之后,程序跳出循环。

    else语句
    与 if 一样, while 和 for 循环后面也可以跟着 else 语句,不过要和break一起连用。
    当循环正常结束时,循环条件不满足, else 被执行;
    当循环被 break 结束时,循环条件仍然满足, else 不执行。
    不执行:

values = [7, 6, 4, 7, 19, 2, 1]
for x in values:
    if x <= 10:
        print 'Found:', x
        break
else:
    print 'All values greater than 10'
#Found: 7


    执行:

In [11]:values = [11, 12, 13, 100]
for x in values:
    if x <= 10:
        print 'Found:', x
        break
else:
    print 'All values greater than 10'
#All values greater than 10


    同样需要注意冒号和缩进。另外,在Python中没有do..while循环。

转载于:https://www.cnblogs.com/mysterious-killer/p/10027313.html

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值