user14410448
user14410448

Reputation:

How to check user input for a specific string

I am trying to write a function to begin my program by asking the user to define an enzyme from a list of 4 possible enzymes. I am trying to use error handling in a while loop to continue asking the user for a valid input if they type in anything that is NOT one of the four enzymes:

def enzyme_select():
    print('The 4 enzymes you may digest this sequence with are:\nTrypsin\nEndoproteinase Lys-C\nEndoproteinase Arg-C\nV8 proteinase (Glu-C)')
    enzyme = ''
    
    while enzyme != 'trypsin' or 'Endoproteinase Lys-C' or 'Endoproteinase Arg-C' or 'V8 proteinase' or 'Glu-C':
        try:
            enzyme = input('Please type the enzyme you wish to digest the sequence with: ')
        except: 
            print('This is not one of the 4 possible enzymes.\nPlease type an enzyme from the 4 options')
            continue
        else:
            break
    print(f'You have selected {enzyme}') 

Is there an easier way to check the user has input one of the four possible enzymes? I know how to use this method to check for integer input, but not how to check for a specific string.

Thanks!

Upvotes: 0

Views: 59

Answers (1)

Olaughter
Olaughter

Reputation: 59

You could try making a list of the possible correct options and looping until one of them match, you could then break the loop upon a match:

def enzyme_select():
    print('The 4 enzymes you may digest this sequence with are:\nTrypsin\nEndoproteinase Lys-C\nEndoproteinase Arg-C\nV8 proteinase (Glu-C)')
    
    allowed_enzymes = [
            'Trypsin',
            'Endoproteinase Lys-C',
            'Endoproteinase Arg-C',
            'V8 proteinase (Glu-C)'
            ]

    while True:
        enzyme = input('Please type the enzyme you wish to digest the sequence with: ')
        # Check here if the input enzyme is one of the allowed values
        if enzyme in allowed_enzymes:    
            break
        else:
            print('This is not one of the 4 possible enzymes.\nPlease type an enzyme from the 4 options')
            continue
    
    print(f'You have selected {enzyme}') 

Upvotes: 1

Related Questions