Skip to main content
 首页 » 编程设计

python之验证列表

2025年05月04日18lyj

我正在尝试使用包含有效输入字符串的列表来验证输入,但我似乎无法使其正常工作,有什么帮助吗?

choice = ["A","a","B","b"] 
def main(): 
    test = input() 
    if validate(test): 
        print("Entered a") 
    else: 
        print("did not enter a") 
 
def validate(val): 
    try:  
        val = choice.index[1] 
    except: 
        return False 
    else: 
        return True 
main() 

请您参考如下方法:

验证不需要异常,只需使用 in 运算符检查列表是否包含该元素:

def validate(val): 
    if val in choice: # checks if the value is in the list. 
        return True 

validate() 中也不需要 else 子句,因为该函数将返回 None,其计算结果为 False。


为了让它变得更好,只需返回元素(它将再次评估为 True):

choice = ["A","a","B","b"] 
def main(): 
    test = input() 
    if validate(test): 
        print("Entered " + val) 
    else: 
        print("Did not enter a valid value") 
 
def validate(val): 
    if val in choice: 
        return val