Python 中的 "Do you want to continue?" 类型案例有问题

Trouble with "Do you want to continue?" type cases in Python

场景如下:

我有一个功能,要求用户输入 select m 列表中的 n[=39] 项=] 项目(给定 m <= n)。仅供参考,如果他愿意,他可能会输入错误的值,在这种情况下,系统会询问他是否要重新开始,但如果他输入正确的值,则一切正常。我被前一部分卡住了。

这是我的代码,我知道这是错误的,所以不需要惩罚我!

column_names = ["DWUXZ", "bKDoH", "erLlI", "QJAfR", "dAfNn", "kpwGt", "fuDmY", "WoTau", "qrFaZ", "ZGSkx"] #The list to choose the items from

def newfunc():

    print (f"Here is the list of columns to choose from: {column_names}\n"
    args = input ("Enter column names separated by comma (Hit enter to select all columns).\n").split(',')

    userinputs_notfound = [] #This will hold the wrong entries entered by the user.
    for arg in args:
        if arg.replace(" ", "") not in column_names:
            userinputs_notfound.append(arg.replace(" ", ""))
    
    if len(userinputs_notfound) == 0:
        pass
    else:
        while input("Do you want to continue? [Y/n]: ").lower() == 'y':
            newfunc() #Recursively calling the function

newfunc() #Calling the function.

我无法正确理解 while 部分。简而言之,这是我希望它执行的操作:

  1. 用户可以选择 select 给定列表中的字符串(称为 column_names
  2. 他故意输入错误的值
  3. 脚本显示“未找到这些条目。您想再试一次吗?[Y/n]
  4. 当用户点击 Y 时,它返回并再次执行整个操作。
  5. 如果他selects ,则退出循环

对于我来说,我无法做到这一点。

非常感谢任何帮助。

整个 body 应该在一个 while 循环中,一旦输入正确,您就会跳出该循环。不要像这样无限制地使用递归。

column_names = set(["DWUXZ", "bKDoH", "erLlI", "QJAfR", "dAfNn", "kpwGt", "fuDmY", "WoTau", "qrFaZ", "ZGSkx")

def newfunc():

    while True:
        print (f"Here is the list of columns to choose from: {column_names}\n"
        args = input ("Enter column names separated by comma (Hit enter to select all columns).\n").split(',')
        if all(arg.replace(" ", "") in column_names for arg in args):
            break
           
        missing = set(args) - column_names
        if missing:
            print(f"Missing: {missing}")
            response = input("Do you want to try again?")
            if response.lower() == "n":
                break

要么将整个函数体放在 for 循环中,并省略递归调用:

def foo():
    while x:
        do_stuff
        change_x

或省略 while 循环并使用条件 if 语句保持递归:

def foo():
    do_stuff
    if condition:
        foo()

否则您将继续调用该函数,因此您需要转义您在程序 运行 期间创建的每个 while input() == 'y' 循环,无论可能有多少循环。

至于'hit enter to keep select all columns:

if arg == ['']:
    arg = column_names

对照 [''] 检查,因为您拆分了用户输入。

对您的代码进行了一些重构:

(也解决了 'enter to select all columns' 问题。)

# The list to choose the items from
column_names = ["DWUXZ", "bKDoH", "erLlI", "QJAfR", "dAfNn", "kpwGt",
                "fuDmY", "WoTau", "qrFaZ", "ZGSkx"]

def get_input():
    print(f"Here is the list of columns to choose from: {column_names}\n")
    args = input("Enter column names separated by comma "
                  "(Hit enter to select all columns).\n").strip().split(',')
    return args


while True:
    args = get_input()
    if len(args) == 1 and args[0] == '':  # pressed enter
        print('OK. Selected all columns')
        break

    # This will hold the wrong entries entered by the user.
    userinputs_notfound = []
    for arg in args:
        if arg.replace(" ", "") not in column_names:
            userinputs_notfound.append(arg.replace(" ", ""))

    if not userinputs_notfound:
        print('OK')
        break

    should_quit = input("Do you want to continue? [Y/n]: ").lower() == 'n'
    if should_quit is True:
        break

输出:

Here is the list of columns to choose from: ['DWUXZ', 'bKDoH', 'erLlI', 'QJAfR', 'dAfNn', 'kpwGt', 'fuDmY', 'WoTau', 'qrFaZ', 'ZGSkx']

Enter column names separated by comma (Hit enter to select all columns).
DWUXZ, bKDoH
OK
Here is the list of columns to choose from: ['DWUXZ', 'bKDoH', 'erLlI', 'QJAfR', 'dAfNn', 'kpwGt', 'fuDmY', 'WoTau', 'qrFaZ', 'ZGSkx']

Enter column names separated by comma (Hit enter to select all columns).
fda, fdax
Do you want to continue? [Y/n]: n
Here is the list of columns to choose from: ['DWUXZ', 'bKDoH', 'erLlI', 'QJAfR', 'dAfNn', 'kpwGt', 'fuDmY', 'WoTau', 'qrFaZ', 'ZGSkx']

Enter column names separated by comma (Hit enter to select all columns).
fda, dax
Do you want to continue? [Y/n]: y
Here is the list of columns to choose from: ['DWUXZ', 'bKDoH', 'erLlI', 'QJAfR', 'dAfNn', 'kpwGt', 'fuDmY', 'WoTau', 'qrFaZ', 'ZGSkx']

Enter column names separated by comma (Hit enter to select all columns).
Here is the list of columns to choose from: ['DWUXZ', 'bKDoH', 'erLlI', 'QJAfR', 'dAfNn', 'kpwGt', 'fuDmY', 'WoTau', 'qrFaZ', 'ZGSkx']

Enter column names separated by comma (Hit enter to select all columns).

OK. Selected all columns
column_names = ["DWUXZ", "bKDoH", "erLlI", "QJAfR", "dAfNn", "kpwGt", "fuDmY", "WoTau", "qrFaZ", "ZGSkx"]

def newfunc():

print (f"Here is the list of columns to choose from: {column_names}\n") //correction
args = input("Enter column names separated by comma (Hit enter to select all columns).\n").split(',')

userinputs_notfound = [] #This will hold the wrong entries entered by the user.
for arg in args:
    if arg.replace(" ", "") not in column_names:
        userinputs_notfound.append(arg.replace(" ", ""))

if len(userinputs_notfound) == 0:
    pass
else:
    if input("Do you want to continue? [Y/n]: ").lower() == 'y': //correction no need of while
        newfunc()

newfunc() #Calling the function.

这个适用于 python 3.8+

# The list to choose from
col_names = ["DWUXZ", "bKDoH", "erLlI", "QJAfR", "dAfNn", "kpwGt", "fuDmY", "WoTau", "qrFaZ", "ZGSkx"]

def newFunc():
    # Print all the available column names.
    print("List of columns to choose from:\n", *col_names, sep = '\n')

    # Filter out the missing names (if any) and ask for the prompt.
    # The anonymous function inside lambda match against the empty
    # string when the user chooses to select all.
    while missing := list(filter(lambda name: name and name not in col_names,
    input("\nEnter column names separated by comma (Hit enter to select all): ").split(','))):
        
        print("Missing:", *missing, sep = '\n')
        # Break the loop for any of the negetive response.
        if input("\nDo you want to continue? ").lower() in ['n', "no", "nope", "nah"]:
            break

    # Implement here your logic when no missing is found.


# Call the function.
newFunc()

在赋值运算符的帮助下 := 我们只用了几行代码就做到了。