Why does python use 'else' after for and while loops?

前端 未结 21 1872
爱一瞬间的悲伤
爱一瞬间的悲伤 2020-11-21 06:57

I understand how this construct works:

for i in range(10):
    print(i)

    if i == 9:
        print(\"Too big - I\'m         


        
21条回答
  •  终归单人心
    2020-11-21 07:23

    for i in range(3):
        print(i)
    
        if i == 2:
            print("Too big - I'm giving up!")
            break;
    else:
        print("Completed successfully")
    

    "else" here is crazily simple, just mean

    1, "if for clause is completed"

    for i in range(3):
        print(i)
    
        if i == 2:
            print("Too big - I'm giving up!")
            break;
    if "for clause is completed":
        print("Completed successfully")
    

    It's wielding to write such long statements as "for clause is completed", so they introduce "else".

    else here is a if in its nature.

    2, However, How about for clause is not run at all

    In [331]: for i in range(0):
         ...:     print(i)
         ...: 
         ...:     if i == 9:
         ...:         print("Too big - I'm giving up!")
         ...:         break
         ...: else:
         ...:     print("Completed successfully")
         ...:     
    Completed successfully
    

    So it's completely statement is logic combination:

    if "for clause is completed" or "not run at all":
         do else stuff
    

    or put it this way:

    if "for clause is not partially run":
        do else stuff
    

    or this way:

    if "for clause not encounter a break":
        do else stuff
    

提交回复
热议问题