3

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)
Mike67
  • 11,175
  • 2
  • 7
  • 15

6 Answers6

1

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)
Green Cloak Guy
  • 23,793
  • 4
  • 33
  • 53
  • It does not seem to work if the user inputs just for example "1". – Brasilian_student Nov 11 '20 at 19:05
  • @Brasilian_student It works on my machine. `str.split()` just returns a list containing just the input if the input doesn't contain the string it's supposed to split on. If you input literally `"1"` then you need to get rid of the quotation marks for it to work, but if you input `1` without quotes, which is what you should be doing, then it should work. – Green Cloak Guy Nov 11 '20 at 19:07
0
while True:
order = input("Input value: ")
try:
    if "," in order:
        list_order = order.split(",")
        list_numbers = []
        while list_order:
            clipboard = list_order[0]
            if clipboard != "1" or clipboard != "2" or clipboard != "3":
                del list_order[0]
            elif clipboard == "1" or clipboard == "2" or clipboard == "3":
                list_numbers.insert(-1, clipboard)
                del list_order[0]
            
        print(list_numbers)
        print(list_order)
        break
    else:
        print("\nError. Try again!\n")
except:
    pass

This isn't the best result. But is it a good example for testing every letter by letter. :) I hope I could help you, and it not, maybe you learned something new :)

Henrik
  • 828
  • 8
  • 34
0
why dont you make a list of possible inputs and check if input for user is present in that list?

inputList = []
inputList.append("1")
inputList.append("2")
inputList.append("3")
inputList.append("1,2")
inputList.append("1,3")
inputList.append("2,3")
inputList.append("2,1")
inputList.append("3,1")
inputList.append("3,2")
inputList.append("1,2,3")
inputList.append("1,3,2")
inputList.append("2,1,3")
inputList.append("2,3,1")
inputList.append("3,2,1")
inputList.append("3,1,2")
while True:

    order = input("Input value: ")
    try:
        if order in inputList:
            list_order = order.split(",")
            break

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

print(list_order)
0
# In case your needs should ever change (for example also allowing '-')
# You can put anything you want int this list.
valid_characters = ['1', '2', '3', '4', '5', '6', '7', '8', '9', '0', ',']
 
 
while True:
    order = input("Input value: ")

    try:
        # we use `set()` to get each unique character. For example: 
        # "1,2,33,4516,14" would just be {'1', '6', '3', '4', '2', '5', ','}
        for char in set(order):
            if char not in valid_characters:
                # raise an exception of type ValueError
                raise ValueError

    # The exception gets handled here
    except ValueError:
        print("\nError. Try again!\n")
        # And we go back to the top
        continue


    list_order = order.split(',')

    print(list_order, end="\n\n")

Let me know if you have any questions or if some parts are not clear enough.

TheThird
  • 56
  • 1
  • 4
0

This code does what you want.

import re

def isValid(order):
    if(re.fullmatch('[1-3]([ \t]*,[ \t]*[1-3])*', order)):
        print("true")
        return True
    else:
        return False


while True:
    order = input("Input value: ")

    try:
        if isValid(order):
            list_order = order.split(",")
            break

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

I created a function that uses regular expressions to check validity.

Dharman
  • 30,962
  • 25
  • 85
  • 135
Berdan Akyürek
  • 212
  • 1
  • 14
0

This is another answer similar to my previous answer in which you told that what if support numbers goes to 9. So here is the solution for that using itertools library. you can change the for loop range as per you requirement

from itertools import permutations 
    inputList  = []
    for i in range(1,10)
        perm = permutations(["1", "2", "3","4","5","6","7","8","9"],i)
        for i in list(perm):
            inputList.append(','.join(list(i)))
    
    while True:
        order = input("Input value: ")
        try:
            if order in inputList:
                list_order = order.split(",")
                break
    
            else:
                print("\nError. Try again!\n")
                continue
        except:
            pass
    
    print(list_order)