maramingsalamat
maramingsalamat

Reputation: 25

How to end a while Loop when a desired input is given?

My program takes an input from the user about what they want to add. This works fine, but the problem arises when it comes down to the nested while loop that promps the user if they wish to add more items (y/n). I want y to start the loop from the beginning, n to exit the loop and continue the program, and any other input to give an error whilst restarting the y/n prompt. I can't seem to figure out how to get out of the nested while loop nor can I figure out how to throw an error if the input is neither y or n. How would I go about fixing this?

elif user_input == "a":
    while True:
        try:
            add_item = input("What item would you like to add? ").lower()
            if not re.match("^[a-z, A-Z]*$", add_item):
                print("ERROR: Only letters A-Z are allowed!")
                continue
            elif len(add_item) < 1 or len(add_item) > 20:
                print("Item name is too long, only a maximum of 20 characters are allowed!")
                continue
            else:
                item_amount = int(input("How many of these would you like to add? "))
                shopping_list[add_item] = item_amount
                print(f"{item_amount}x {add_item.title()} added to the shopping list.\n")
            while True:
                try:
                    add_more = input("Would you like to add more items? (y/n): ").lower()
                    if add_more == "y":
                        break
                    elif add_more == "n":
                        break
                except TypeError:
                    print("ERROR: Expected y or n in return! Try again!.\n")
                    break
        except ValueError:
            print("\nERROR: Amount must be an integer! Try adding an item again!\n")

Upvotes: 0

Views: 717

Answers (1)

Lazy Ren
Lazy Ren

Reputation: 914

  1. use boolean variable(keep_adding for below code) to decide while loop's terminal condition. It will be set to False iff add_more == "n"

  2. use raise TypeError to raise error if user input is neither "y" nor "n".

  3. You should remove break from except TypeError in order to keep asking "Would you like to add more items? (y/n): " if input is invalid.

elif user_input == "a":
    keep_adding = True
    while keep_adding:
        try:
            add_item = input("What item would you like to add? ").lower()
            if not re.match("^[a-z, A-Z]*$", add_item):
                print("ERROR: Only letters A-Z are allowed!")
                continue
            elif len(add_item) < 1 or len(add_item) > 20:
                print("Item name is too long, only a maximum of 20 characters are allowed!")
                continue
            else:
                item_amount = int(input("How many of these would you like to add? "))
                shopping_list[add_item] = item_amount
                print(f"{item_amount}x {add_item.title()} added to the shopping list.\n")
            while True:
                try:
                    add_more = input("Would you like to add more items? (y/n): ").lower()
                    if add_more == "y":
                        break
                    elif add_more == "n":
                        keep_adding = False
                        break
                    else:
                        raise TypeError
                except TypeError:
                    print("ERROR: Expected y or n in return! Try again!.\n")
        except ValueError:
            print("\nERROR: Amount must be an integer! Try adding an item again!\n")

Upvotes: 2

Related Questions