多个if条件,无嵌套

Ray*_* C. 5 python if-statement while-loop python-3.x

我下面有一个示例代码,需要一些帮助。该代码在开始时将'结果'变量设置为False,并且只有在满足所有'if'条件的情况下,才应将其设置为True。有更有效的方法吗?我试图避免嵌套的“ if”语句。

谢谢!

    outcome = False

    while True:
        if a != b:
            print("Error - 01")
            break

        if a["test_1"] != "test_value":
            print("Error - 02")
            break

        if "test_2" not in a:
            print("Error - 03")
            break

        if a["test_3"] == "is long data string":
            print("Error - 04")
            break

        outcome = True
        break
Run Code Online (Sandbox Code Playgroud)

Dum*_*imp 4

我会这样写,所以函数一旦遇到错误就结束,而最可能的错误应该在最上面,如果遇到那个错误,就会返回False并结束函数。否则,它将检查所有其他错误,然后最终得出结论:结果确实为真。

# testOutcome returns a boolean
outcome = testOutcome(a,b)

# Expects a and b
# Breaks out of the function call once error happens
def testOutcome(a,b):
    # Most likely error goes here
    if a != b:
        print("Error - 01")
        return False

    # Followed by second most likely error
    elif a["test_1"] != "test_value":
         print("Error - 02")
         return False

    # Followed by third most likely error
    elif "test_2" not in a:
         print("Error - 03")
         return False

    # Least likely Error
    elif a["test_3"] == "is long data string":
         print("Error - 04")
         return False

    else:
        return True
Run Code Online (Sandbox Code Playgroud)