'Add yes/no confirmation in python 3.X [closed]

I have a function that allows a user the ability to add data via input. I would like to add a confirmation step that will allow them to answer yes or no to continue. If they select no it should allow them to restart the function of adding data to the list. I also want to make sure they answer with Y, YES, y, yes, N, NO, n, no. What would be the best way to accomplish this? I've tried several solution I've found online but I end up not being able to get out of the loop of asking yes or no. Thanks in advance.

def item_list():  # Create a list 
    items = []
    item_int = 0
    while 1:
        item_int += 1
        item = input("\nEnter item %d or Press Enter: " % item_int)
        if item == "":
            break
        items.append(item)
    return items


items = item_list()
print(items)


Solution 1:[1]

You could create a wrapper function which calls your other function. In the wrapper function, use another loop to confirm items.

# wrapper function
def item_list_wrapper():
    while True:
        # call your function at the start of each iteration
        final_items = item_list()

        # confirm with the user
        print('\nThese are your items:', ', '.join(final_items))
        user_input = input('Confirm? [Y/N] ')
      
        # input validation  
        if user_input.lower() in ('y', 'yes'):
           break
        elif user_input.lower() in ('n', 'no'):  # using this elif for readability
           continue
        else:
           # ... error handling ...
           print(f'Error: Input {user_input} unrecognised.')
           break

    return final_items

# your original function
def item_list():
    items = []
    item_int = 0

    while 1:
        item_int += 1
        item = input("\nEnter item %d or Press Enter: " % item_int)
        if item == "":
            break
        items.append(item)
    return items

Then call it as you'd normally call it.

items = item_list_wrapper()
print(items)

In the item_list_wrapper function, note that the line with items = item_list() will renew the list every time. If you want the user to continue adding existing items, you could switch the order of commands around.

def item_list_wrapper():

    final_items = item_list()  # call the function at the start

    while True:
        # confirm with the user
        print('\nThese are your items:', ', '.join(final_items))
        user_input = input('Confirm? [Y/N] ')

        # input validation
        if user_input.lower() in ('y', 'yes'):
           break
        elif user_input.lower() not in ('n', 'no'):
           # ... error handling ...
           print(f'Error: Input {user_input} unrecognised.')
           break

        # call your function at the start of each iteration
        new_items = item_list()

        # add new items to previous items
        final_items += new_items

    return final_items
   

Solution 2:[2]

answer = input("Continue?")
if answer.lower() in ["y","yes"]:
     # Do stuff
else if answer.lower() in ["n","no"]:
     # Do other stuff
else:
     # Handle "wrong" input

Solution 3:[3]

My answer would be extension of @B. Plüster but it allows slightly bigger range of the inputs and prevent rejections of case-sensitive typos:

answer = input("Continue?")
if answer.upper() in ["Y", "YES"]:
    # Do action you need
else if answer.upper() in ["N", "NO"]:
    # Do action you need

Solution 4:[4]

Don't know whether this is efficient enough.

    items = list()
    tr = [" Y", "YES", "y", "yes"]
    fs = ["N", "NO", "n", "no"]
    item_int = 0
    def item_list():  # Create a list
        global  item_int
        global items
        response = input("\nDo you want to enter data: ")
        if response == "":
            return
        if response in tr:
            item_int += 1
            item = input("\nEnter item %d or Press Enter: " % item_int)
            items.append(item)
        elif response in fs:
            item_int=0
            print("List cleared!")
            items.clear()
        item_list()
    item_list()
    print(items)

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Charles L.
Solution 2
Solution 3 Dmytro Chasovskyi
Solution 4 Silam Arasu