Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Multiple if conditions, without nesting

I have a sample piece of code below that I need some help on. The code sets the 'outcome' variable to False in the beginning and only should become True if all the 'if' conditions are met. Is there a more efficient way of doing this? I am trying to avoid nested 'if' statements.

Thanks!

    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
like image 857
Raymond C. Avatar asked Oct 30 '19 06:10

Raymond C.


People also ask

Can you have multiple conditions in an if statement?

A nested if statement is an if statement placed inside another if statement. Nested if statements are often used when you must test a combination of conditions before deciding on the proper action.

How do you handle multiple if conditions?

The multiple IF conditions in Excel are IF statements contained within another IF statement. They are used to test multiple conditions simultaneously and return distinct values. The additional IF statements can be included in the “value if true” and “value if false” arguments of a standard IF formula.

How do you write an IF THEN statement in Excel with multiple conditions?

Another way to get an Excel IF to test multiple conditions is by using an array formula. To complete an array formula correctly, press the Ctrl + Shift + Enter keys together. In Excel 365 and Excel 2021, this also works as a regular formula due to support for dynamic arrays.


1 Answers

I would write it like this, so the function ends once it encounters an error, and the most likely error should be on top, and if it encounters that error, it will return False and end the function. Else, it will check for all the other errors and then eventually conclude that the outcome is indeed True.

# 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
like image 124
Dumb chimp Avatar answered Oct 12 '22 07:10

Dumb chimp