How to break out of multiple loops?

后端 未结 30 3342
情书的邮戳
情书的邮戳 2020-11-21 05:48

Given the following code (that doesn\'t work):

while True:
    #snip: print out current state
    while True:
        ok = get_input(\"Is this ok? (y/n)\")
          


        
30条回答
  •  终归单人心
    2020-11-21 06:20

    # this version uses a level counter to choose how far to break out
    
    break_levels = 0
    while True:
        # snip: print out current state
        while True:
            ok = get_input("Is this ok? (y/n)")
            if ok == "y" or ok == "Y":
                break_levels = 1        # how far nested, excluding this break
                break
            if ok == "n" or ok == "N":
                break                   # normal break
        if break_levels:
            break_levels -= 1
            break                       # pop another level
    if break_levels:
        break_levels -= 1
        break
    
    # ...and so on
    

提交回复
热议问题