How to break out of multiple loops?

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

    I'd like to remind you that functions in Python can be created right in the middle of the code and can access the surrounding variables transparently for reading and with nonlocal or global declaration for writing.

    So you can use a function as a "breakable control structure", defining a place you want to return to:

    def is_prime(number):
    
        foo = bar = number
    
        def return_here():
            nonlocal foo, bar
            init_bar = bar
            while foo > 0:
                bar = init_bar
                while bar >= foo:
                    if foo*bar == number:
                        return
                    bar -= 1
                foo -= 1
    
        return_here()
    
        if foo == 1:
            print(number, 'is prime')
        else:
            print(number, '=', bar, '*', foo)
    

    >>> is_prime(67)
    67 is prime
    >>> is_prime(117)
    117 = 13 * 9
    >>> is_prime(16)
    16 = 4 * 4
    

提交回复
热议问题