How to break out of multiple loops?

后端 未结 30 3345
情书的邮戳
情书的邮戳 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:21

    First, you may also consider making the process of getting and validating the input a function; within that function, you can just return the value if its correct, and keep spinning in the while loop if not. This essentially obviates the problem you solved, and can usually be applied in the more general case (breaking out of multiple loops). If you absolutely must keep this structure in your code, and really don't want to deal with bookkeeping booleans...

    You may also use goto in the following way (using an April Fools module from here):

    #import the stuff
    from goto import goto, label
    
    while True:
        #snip: print out current state
        while True:
            ok = get_input("Is this ok? (y/n)")
            if ok == "y" or ok == "Y": goto .breakall
            if ok == "n" or ok == "N": break
        #do more processing with menus and stuff
    label .breakall
    

    I know, I know, "thou shalt not use goto" and all that, but it works well in strange cases like this.

提交回复
热议问题