zoukankan      html  css  js  c++  java
  • else配合while或者for循环只用注意点

    当while循环或者for循环配合else使用时注意以下2点:

    while 条件:

      语句块

    else:

      语句块

    1.运行while或者for语句块的时候没有break时,else语句块会在whlie或者for语句块结束后执行else里面的语句块

    while循环:

    count = 0
    while count <= 5 :
        count += 1
        if count == 4:
            continue
        print("Loop",count)
    
    else:
        print("循环正常执行完啦")
    print("-----out of while loop ------")        

    执行结果:

    Loop 1
    Loop 2
    Loop 3
    Loop 5
    Loop 6
    循环正常执行完啦
    -----out of while loop ------

    for循环:

    for i in range(1,6):
        if i == 4:
            continue
        print("Loop",i)
    else:
        print("循环正常执行完啦")
    print("-----out of while loop ------")

    执行结果:

    Loop 1
    Loop 2
    Loop 3
    Loop 5
    循环正常执行完啦
    -----out of while loop ------
    
    Process finished with exit code 0

    2.当运行while或者for语句块的时候有break时,else语句块在whlie或者for语句块结束后不会执行else里面的语句块

    count = 0
    while count <= 5 :
        count += 1
        if count == 4:
            break
        print("Loop",count)
    
    else:
        print("循环正常执行完啦")
    print("-----out of while loop ------")    

    执行结果:

    Loop 1
    Loop 2
    Loop 3
    -----out of while loop ------

    for循环:

    for i in range(1,6):
        if i == 4:
            break
        print("Loop",i)
    else:
        print("循环正常执行完啦")
    print("-----out of while loop ------")

    执行结果:

    Loop 1
    Loop 2
    Loop 3
    -----out of while loop ------
  • 相关阅读:
    CoffeeScript介绍
    在ubuntu下安装rails
    NodeJS扫盲班
    sguID056681
    UVA11865 Stream My Contest(最小树形图)
    POJ1469COURSES(二分图最大匹配)
    UVA1494 Qin Shi Huang's National Road System(最小生成树)
    UVA11478 Halum(差分约束系统)
    二分图最大匹配总结
    POJ1466Girls and Boys(二分图最大独立集)
  • 原文地址:https://www.cnblogs.com/Felix-DoubleKing/p/9656938.html
Copyright © 2011-2022 走看看