如何检查用户输入的特定字符串

2024-10-01 19:27:06 发布

您现在位置:Python中文网/ 问答频道 /正文

我试图编写一个函数,要求用户从4种可能的酶列表中定义一种酶,以此开始我的程序。我尝试在while循环中使用错误处理,如果用户键入的内容不是以下四种酶之一,则继续要求用户输入有效的输入:

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}') 

有没有更简单的方法来检查用户是否输入了四种可能的酶中的一种?我知道如何使用此方法检查整数输入,但不知道如何检查特定字符串

谢谢


Tags: orthe用户youwithargprintsequence
1条回答
网友
1楼 · 发布于 2024-10-01 19:27:06

您可以尝试列出可能正确的选项并循环,直到其中一个匹配,然后在匹配时中断循环:

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}') 

相关问题 更多 >

    热门问题