验证码

jam*_*ean 0 python validation

我正在尝试验证字符串的有效性,以确保它是一个合法的命令,我可以传递给终端.如果字符串通过测试,我返回True.否则,我返回False和错误消息.

我的代码非常丑陋,有很多嵌套的if语句 - 我怎样才能改进它?

task = task.split()
if len(task) > 1: 
    if task[0] == 'svn':
        if task[1] in ALLOWED:
            if len(task[2:]) == ALLOWED[task[1]]:
                return True, task, None
            else:
                return False, "Incorrect number of arguments."
        else:
            return False, "Not a legal command."    
    else:
        return False, "Not a subversion command."
else:
    return False, "Invalid input"
Run Code Online (Sandbox Code Playgroud)

Mar*_*ers 5

而不是正面检查和嵌套if语句:

if a:
    if b:
        if c:
            foo()
        else:
            # error 3
     else:
         # error 2
else:
    # error 1
Run Code Online (Sandbox Code Playgroud)

你可以扭转逻辑并纾困,除非一切正常:

if not a:
    # raise an exception

if not b:
    # raise an exception

if not c:
    # raise an exception

# If we get here, everything is OK.
foo()
Run Code Online (Sandbox Code Playgroud)

这样可以更轻松地查看哪个错误消息与哪个条件匹配.