Home > Back-end >  how to handle user input in list if it is not an integer prompt back the user
how to handle user input in list if it is not an integer prompt back the user

Time:01-16

i'm looking to handle the way a user input in a list if the user enter a letter(string) instead of a number(integer) it prompt back the user that he entered an invalid value and prompt back the user for another try. here some code :

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

CodePudding user response:

You can use this code.

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

CodePudding user response:

I recommend using an exception handler (try/except). Here's one way to do it:

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())

CodePudding user response:

You could use a try, except statement. If the int() fails, it will throw a exception which we handle.

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

Full code:

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
  •  Tags:  
  • Related