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)
3
  • Add all the variations to a string list, then use if order in mystringlist: You can also write code to get all permutations of 1,2,3. Commented Nov 11, 2020 at 18:55
  • That's a good idea, but I'd still need to put all their combinations on the code. Commented Nov 11, 2020 at 19:00
  • Check this post: stackoverflow.com/questions/104420/… Commented Nov 11, 2020 at 19:01

6 Answers 6

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)
Sign up to request clarification or add additional context in comments.

2 Comments

It does not seem to work if the user inputs just for example "1".
@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.
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)

2 Comments

What if we want to add support for numbers way up to 9? hard-coding is not the answer.
then you need to use itertools library to make all permutations and iterate through every combination.
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 :)

Comments

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.

Comments

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.

Comments

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)

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.