zoukankan      html  css  js  c++  java
  • 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循环。

  • 相关阅读:
    python 函数2
    python 函数
    python 中string格式化
    python中的集合
    值&&引用传递&&序列化
    线程&&进程
    c#委托
    .net框架介绍
    类的定义
    ef中关于数据库中int为null问题
  • 原文地址:https://www.cnblogs.com/mysterious-killer/p/10027313.html
Copyright © 2011-2022 走看看