Using flags to jump out of nested (while) loops

We talked about using flags in the lecture on while loops but maybe it is helpful to show an example of how to use them to to jump outside two nested loops:



do_loop = True
while do_loop: # will only enter loop "body" if do_loop == True
    print "in loop 1"
    while True:  # loops until break is encountered
        print "in loop 2"
        ip = raw_input("enter t to exit loop 2, d to exit loop 1, other key to go on ")
        if ip == "t":
            break  # jump out of while True: loop
        elif ip == "d":
            do_loop = False # will make while do_loop: quit
            break  # jump out of while True: loop
    #end of While True: loop - break jumps here
    print "do_loop is", do_loop  # if do_loop == False the next while do_loop test will fail
# end of while do_loop: - setting do_loop to False will get you here

          



Here's the shell log for entering a  -> t -> a -> d :



in loop 1
in loop 2
enter t to exit loop 2, d to exit loop 1, other key to go on a
in loop 2
enter t to exit loop 2, d to exit loop 1, other key to go on t
do_loop is True
in loop 1
in loop 2
enter t to exit loop 2, d to exit loop 1, other key to go on a
in loop 2
enter t to exit loop 2, d to exit loop 1, other key to go on d
do_loop is False

No comments:

Search This Blog