• 技术文章 >常见问题 >Python常见问题

    python循环结构中的else怎么使用

    silencementsilencement2019-11-07 09:32:00原创2179

    循环组合中的else执行的情况下是循环正常结束(即不是使用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')
       
    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')

    执行结果如下:

    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

    python学习网,大量的免费python学习视频,欢迎在线学习!

    专题推荐:else
    上一篇:学python用什么书 下一篇:怎么停止python脚本

    相关文章推荐

    • python中if语句的用法及if-else结构的使用• Python if else条件语句详解• Python - if-else 的多种简洁写法

    全部评论我要评论

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

  • 取消发布评论
  • 

    Python学习网