在 python 3.X 中添加是/否确认

JHC*_*Tac 7 python python-3.x

我有一个功能,允许用户通过输入添加数据。我想添加一个确认步骤,让他们回答“是”或“否”才能继续。如果他们选择“否”,则应允许他们重新启动将数据添加到列表的功能。我还想确保他们回答 Y、YES、y、yes、N、NO、n、no。实现这一目标的最佳方法是什么?我尝试了在网上找到的几种解决方案,但最终无法摆脱询问“是”或“否”的循环。提前致谢。

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)
Run Code Online (Sandbox Code Playgroud)

B. *_*ter 15

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
Run Code Online (Sandbox Code Playgroud)

  • @roganjosh 这取决于应用程序。如果你想写“黄色”怎么办? (2认同)

Tre*_*edJ 0

您可以创建一个调用其他函数的包装函数。在包装函数中,使用另一个循环来确认项目。

# 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
Run Code Online (Sandbox Code Playgroud)

然后像平常那样称呼它。

items = item_list_wrapper()
print(items)
Run Code Online (Sandbox Code Playgroud)

item_list_wrapper函数中,请注意 with 行items = item_list()每次都会更新列表。如果您希望用户继续添加现有项目,您可以交换命令的顺序。

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
   
Run Code Online (Sandbox Code Playgroud)