【问题标题】:Trouble with "Do you want to continue?" type cases in Python“你想继续吗?”的问题Python中的类型案例
【发布时间】:2020-11-05 06:13:10
【问题描述】:

这是场景:

我有一个要求用户输入的功能 - 从 n 个项目的列表中选择 m 个项目(给定 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. 用户可以选择从给定列表中选择字符串(称为column_names
  2. 他故意输入错误的值
  3. 脚本显示“未找到这些条目。您要再试一次吗?[Y/n]
  4. 当用户点击 Y 时,它会返回并再次执行整个操作。
  5. 如果他选择,则退出循环

为了我的一生,我无法做到这一点。

非常感谢任何帮助。

【问题讨论】:

    标签: python python-3.x while-loop user-input


    【解决方案1】:

    这个是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()
    

    在赋值运算符:= 的帮助下,我们在几行代码内完成了这项工作。

    【讨论】:

      【解决方案2】:

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

      def foo():
          while x:
              do_stuff
              change_x
      

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

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

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

      至于'按回车键保持选择所有列:

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

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

      【讨论】:

        【解决方案3】:
        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.
        

        【讨论】:

        • 一切都是完美的,在条件下删除并写入
        【解决方案4】:

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

        (也解决了“输入以选择所有列”的问题。)

        # 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
        

        【讨论】:

        • 请稍作调整,但可以正常工作。谢谢。
        【解决方案5】:

        整个主体应该处于一个 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
        

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 2015-11-29
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多