【问题标题】:how to handle user input in list if it is not an integer prompt back the user如果列表中不是整数提示用户如何处理用户输入
【发布时间】:2022-01-15 11:29:01
【问题描述】:

如果用户输入字母(字符串)而不是数字(整数),我正在寻找处理用户在列表中输入的方式,它会提示用户他输入了无效值并提示用户再试一次。 这里有一些代码:

def get_list_from_user():   # Prompt the user for a list of number
    while True:
        user_list = input(f"Enter {difficulty} number separated by space: ")
        user_list = user_list.split()
        user_list = [int(i) for i in user_list]
        if not len(user_list) == difficulty:
            print(f"Please chose {difficulty} number separated by space: ")
        else:
            break

    saved_user_list = user_list
    return saved_user_list

【问题讨论】:

  • user_list = [int(i) ...] 行包装在try: except ValueError: continue 部分中(在 continue 语句之前打印可选的错误消息。

标签: python python-3.x list


【解决方案1】:

您可以使用此代码。

def get_list_from_user():   # Prompt the user for a list of number
    while True:
        user_list = input(f"Enter {difficulty} number separated by space: ")
        user_list = user_list.split()
        try:
            user_list = [int(i) for i in user_list ]
        except:
            print("entered an invalid value")
            continue
        if not len(user_list) == difficulty:
            print(f"Please chose {difficulty} number separated by space: "           
        else:
            break

    saved_user_list = user_list
    return saved_user_list

【讨论】:

  • 使用此代码。
【解决方案2】:

我建议使用异常处理程序(try/except)。这是一种方法:

difficulty = 3

def get_list_from_user():   # Prompt the user for a list of number
    while True:
        user_list = input(f"Enter {difficulty} numbers separated by space: ").split()
        try:
            user_list = [int(i) for i in user_list]
            if len(user_list) != difficulty:
                raise ValueError
            return user_list
        except ValueError:
            print('Invalid input')

print(get_list_from_user())

【讨论】:

    【解决方案3】:

    您可以使用 try, except 语句。如果 int() 失败,它会抛出一个我们处理的异常。

            try:
                user_list = [int(i) for i in user_list]
            except ValueError:
                print("Invalid value")
    

    完整代码:

    def get_list_from_user():   # Prompt the user for a list of number
        while True:
            user_list = input(f"Enter {difficulty} number separated by space: ")
            user_list = user_list.split()
            try:
                user_list = [int(i) for i in user_list]
            except ValueError:
                print("Invalid value")
                continue
        
            if not len(user_list) == difficulty:
                print(f"Please chose {difficulty} number separated by space: ")
            else:
                break
    
        saved_user_list = user_list
        return saved_user_list
    

    【讨论】:

      猜你喜欢
      • 2022-12-17
      • 2020-06-22
      • 1970-01-01
      • 2022-01-23
      • 2015-12-24
      • 1970-01-01
      • 2023-03-09
      • 1970-01-01
      相关资源
      最近更新 更多