'How to avoid repeating the same 'else' statement in multiple nested if/else?

In the code below, 'else' is same for all 'if' statements? Is there a way to have just one 'else' statement, rather than repeating the same code in all 'if' statement blocks for 'else' statement?

Here's example:

if condition A == "Yes":
    print("A")
    if condition B == "Yes":
        print("B")
    else:
        print("D")
        if condition C =="Yes":
            print("C")
        else:
            print("D")
else:
    print("D")

Flowchart



Solution 1:[1]

In the case of nested if else, you can use a guard type statement. guard is popular in case of nested if-else and provides a clean code.

Guard statement tries to element the else cases first. You know we write else cases to perform deviated paths. So what if we remove the deviated paths first.

For example, if you have

if condition A == "Yes":
    print("A")
    if condition B == "Yes":
        print("B")
    else:
        print("D")
        if condition C =="Yes":
            print("C")
        else:
            print("D")
else:
    print("D")

Now I can formatting the following

// 1 
if condiation A == "No" {
    print("D")
    return 
}

// 2
if condition B == "Yes" {
    print("B")
    return 
}

if condition C == "No" {
   print("D")
   return 
}

print("C")

For more follow the link: - Youtube

Solution 2:[2]

You look like in a nested testing sequence

You test A if A ok, you test B if B ok you test C

if any test fail you print D

so ... you eitheir leave the testing sequence test everything print all Yes result or print D if any test fail (wich look like a big ERROR message)

or you keep the ugly if else sequence

Solution 3:[3]

If you go for testing everything you can create a function

def TestThis(Value, id):
    if value == "Yes":
        print(id)
        return 1
    else:
        return 0

and call it like this:

if TestThis(A, "A") == 0:
    integrity = 1
elif TestThis(B, "B") == 0:
    integrity = 1
elif TestThis(C, "C") == 0:
    integrity = 1
if integrity == 1:
    print("D")

And I'm pretty sure you can find a way to finally get your sequence testing.

Edited to create that sequential testing that was the aim from the start

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Ankur Lahiry
Solution 2 Psycho99
Solution 3 S.B