Skip to content Skip to sidebar Skip to footer

How To Break Out Of Double While Loop In Python?

Newbie python here. How can I break out of the second while loop if a user selects 'Q' for 'Quit?' If I hit 'm,' it goes to the main menu and there I can quit hitting the 'Q' key.

Solution 1:

You nearly have it; you just need to swap these two lines.

elif choice.lower() == "m":
    break
    loop = 0

elif choice.lower() == "m":
     loop = 0
     break

You break out of the nested loop before setting loop. :)

Solution 2:

Change

break
loop = 0

to

loop = 0break

in your elif blocks.

Solution 3:

Use an exception.

classQuit( Exception ): pass

running= Truewhile running:
    choice = main_menu()

    if choice == "1":
        os.system("clear")

        try:
            whileTrue:
                choice = app_menu()

                if choice == "1":

                elif choice == "2":

                elif choice.lower() == "m":
                    break# No statement after break is ever executed.elif choice.lower() == "q":
                    raise Quit
                sendfiles(source, target)

         except Quit:
             running= Falseelif choice == "q":
        running= False

Solution 4:

Use two distinct variables for both loops, eg loop1 and loop2.

When you first press m in the inner loop you just break outside, and then you can handle q separately.

By the way you shouldn't need the inner variable to keep looping, just go with an infinite loop until key 'm' is pressed. Then you break out from inner loop while keeping first one.

Solution 5:

Rename your top loop to something like mainloop, and set mainloop = 0 when q is received.

while mainloop == 1:
    choice = main_menu()
    if choice == "1":
        os.system("clear")

        while loop == 1:
            choice = app_menu()

            if choice == "1":
                source = '%s/%s/external' % (app_help_path,app_version_10)
                target = '%s/%s' % (target_app_help_path,app_version_10)

            elif choice == "2":
                source = '%s/%s/external' % (app_help_path,app_version_8)
                target = '%s/%s' % (target_app_help_path,app_version_8)
            elif choice.lower() == "m":
                loop = 0
                breakelif choice.lower() == "q":
                mainloop = 0break
                break
            sendfiles(source, target)

    # Internal fileselif choice == "q":
        mainloop = 0

Post a Comment for "How To Break Out Of Double While Loop In Python?"