How to break out of multiple loops?

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

    First, ordinary logic is helpful.

    If, for some reason, the terminating conditions can't be worked out, exceptions are a fall-back plan.

    class GetOutOfLoop( Exception ):
        pass
    
    try:
        done= False
        while not done:
            isok= False
            while not (done or isok):
                ok = get_input("Is this ok? (y/n)")
                if ok in ("y", "Y") or ok in ("n", "N") : 
                    done= True # probably better
                    raise GetOutOfLoop
            # other stuff
    except GetOutOfLoop:
        pass
    

    For this specific example, an exception may not be necessary.

    On other other hand, we often have "Y", "N" and "Q" options in character-mode applications. For the "Q" option, we want an immediate exit. That's more exceptional.

提交回复
热议问题