How to break out of multiple loops?

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

    In this case, as pointed out by others as well, functional decomposition is the way to go. Code in Python 3:

    def user_confirms():
        while True:
            answer = input("Is this OK? (y/n) ").strip().lower()
            if answer in "yn":
                return answer == "y"
    
    def main():
        while True:
            # do stuff
            if user_confirms():
                break
    

提交回复
热议问题