• 技术文章 >Python技术 >Python基础教程

    你所不知道的python循环中的else

    silencementsilencement2019-07-23 11:12:41原创2780

    众多语言中都有if else这对条件选择组合,但是在python中还有更多else使用的地方,比如说循环for,或者while都可以和else组合。

    下面简单介绍一下for-else while-else组合

    循环组合中的else执行的情况下是循环正常结束(即不是使用break退出)。如下列代码:

    1

    2

    3

    4

    5

    6

    7

    8

    9

    10

    11

    12

    13

    14

    15

    16

    17

    18

    19

    20

    21

    22

    23

    24

    25

    26

    27

    28

    29

    30

    31

    32

    33

    numbers= [1,2,3,4,5]

    for nin numbers:

        if (n >5):

            print('the value is %d '%(n))

            break

    else:

        print('the for loop does not end with break')

          

    i= 0

    while(numbers[i] <5):

        print('the index %d value is %d'%(i, numbers[i]))

        if (numbers[i] <0) :

            break

        i= i+ 1

    else:

        print('the loop does not end with break')

        

    numbers= [1,2,3,4,5]

    for nin numbers:

        if (n >5):

            print('the value is %d '%(n))

            break

    else:

        print('the for loop does not end with break')

         

    i= 0

    while(numbers[i] <5):

        print('the index %d value is %d'%(i, numbers[i]))

        if (numbers[i] <0) :

            break

        i= i+ 1

    else:

        print('the loop does not end with break')

    执行结果如下:

    1

    2

    3

    4

    5

    6

    7

    C:\Python27>python.exe for_else.py

    thefor loop doesnot end withbreak

    the index0 valueis 1

    the index1 valueis 2

    the index2 valueis 3

    the index3 valueis 4

    the loop doesnot end withbreak


    专题推荐:else
    上一篇:一文搞定Python大小写转换,首字母大写,去除特殊字符 下一篇:python处理Excel的方法之xlrd

    相关文章推荐

    • Python的内建比较函数cmp比较原理剖析• Python对象类型判断与函数重载

    全部评论我要评论

    © 2021 Python学习网 苏ICP备2021003149号-1

  • 取消发布评论
  • 

    Python学习网