Using try and except to verify user’s input in Python

Tags: ,



I’m doing a school project and the user will need to input some values (1, 2 or 3 and their combinations separated by comma). Ex: 2,3,1 or 2,1

I need to prevent the user from typing anything else out of the standard value.

Here’s my attempt, which is working, but looks very dumb. Anyone could think somehow to improve it?

while True:

    order = input("Input value: ")
    try:
        if order == "1" or order == "2" or order == "3" or order == "1,2" or order == "1,3" or 
            order == "2,3" or order == "2,1" or order == "3,1" or order == "3,2" or order == "1,2,3" 
                or order == "1,3,2" or order == "2,1,3" or order == "2,3,1" or order == "3,2,1" or order == "3,1,2":
            list_order = order.split(",")
            break

        else:
            print("nError. Try again!n")
            continue
    except:
        pass

print(list_order)

Answer

Instead of waiting to .split() the order until after checking the order components are correct, do it beforehand. Then, make a set out of that, and check whether it’s a subset of the correct/acceptable values. Using a set means that order doesn’t matter for this check.

while True:
    order = input('Input Value: ')
    list_order = order.split(',')
    try:
        if set(list_order) <= set(['1', '2', '3']): 
            break
        else:
            print("nError. Try again!n")
            continue
    except:
        pass

print(list_order)


Source: stackoverflow