adding user input of alphabets, not in sequence order

Viewed 30

The program reads a product code, consisting from letter A to L. The user input have to be at least 3 characters long and may be unsorted. I've done the code as shown below. However, the code only accepts the alphabets when its in sequence, eg. abcd..if I input badc, it will become invalid. How do I fix this? Also i can't seem to break from the while loop.

def addProductCode():
    while True:
        partIds = 'ABCDEFGHIJKL'
        productCode = []
        pcode = input("Enter new product code: ").upper()
        if len(pcode) < 3:
            print("The product code is invalid")
        elif pcode not in partIds:
            print("The product code is invalid")
        elif pcode in productCode:
            print("The product code already exists")
        elif pcode == 0:
            break
        else:
            pcode = sorted(pcode)
            productCode.append(pcode)
            print("The product code has been added successfully")
addProductCode()

Desired output:

Enter new product code: zadg

The product code is invalid

Enter new product code: badc

The product code has been added successfully

Enter new product code: abdc

The product code already exists

1 Answers

pcode in partIds checks whether pcode is a substring of partIds, which for example 'BACD' isn't (because the order of characters in a string matters).

If you want to check whether every character in pcode is contained in partIds, either use all and a generator expression:

all(c in partIds for c in pcode)

or use sets:

set(pcode).issubset(partIds)

(Note that for simplicity I have omitted the logical negation – since you are actually using pcode not in partIds you will have to add not in front of either of the two expressions you decide to use.)

Related