Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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)
like image 865
Brasilian_student Avatar asked May 07 '26 13:05

Brasilian_student


1 Answers

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)
like image 143
Green Cloak Guy Avatar answered May 09 '26 04:05

Green Cloak Guy



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!