我正在尝试验证字符串的有效性,以确保它是我可以传递给终端的合法命令。如果字符串通过了测试,我将返回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"发布于 2012-07-31 06:57:17
代替肯定检查和嵌套的if语句:
if a:
if b:
if c:
foo()
else:
# error 3
else:
# error 2
else:
# error 1你可以反其道而行之,除非一切正常:
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()这样可以更容易地查看哪条错误消息与哪条条件匹配。
发布于 2012-07-31 07:00:30
以下是Mark Byer的答案如何具体针对您的案例的一个示例:
task = task.split()
if len(task) < 2:
return False, "Invalid input"
if task[0] != 'svn':
return False, "Not a subversion command."
if task[1] not in ALLOWED:
return False, "Not a legal command."
if len(task[2:]) != ALLOWED[task[1]]:
return False, "Incorrect number of arguments."
return True, task, Nonehttps://stackoverflow.com/questions/11730849
复制相似问题