如何检查条件

时间:2014-09-12 08:13:39

标签: python conditional-statements

这可能不是编程逻辑问题,但最好使用类型。我有以下两种方式,这可能是最好的使用方式。如果还有其他方式,我将非常乐意知道。

条件/值

permission = True
user = {"id": 1, "username": "it.dumb", "password": "", "locked": True}

第一部分

if not permission:
    return "Error, you are not permitted"

if not user:
    return "Error, user not found"

if not user["locked"]:
    return "Error, user is not locked"

user["locked"] = False
return user

第二部分

if permission:
    if user:
        if user["locked"]:
            user["locked"] = False
            return user
        else:
            return "Error, user is not locked"
    else:
        return "Error, user not found"
else:
    return "Error, you are not permitted"

假设这两个代码在方法内;)

1 个答案:

答案 0 :(得分:3)

一个非常pythonic的答案 - 扁平比嵌套好,并且比请求许可更好地请求宽恕。

class AuthenticationError(Exception):
    pass

 ....

if not permission:
    raise AuthenticationError("Error, you are not permitted")

if not user:
    raise AuthenticationError("Error, user not found")

if not user["locked"]:
    raise AuthenticationError("Error, user is not locked")

user["locked"] = False
return user