As a Python developer, you may have come across situations where you need to use multiple if-else statements to check for different conditions. While this approach works, it can make your code bulky and hard to read. In this post, we will explore some ways to reduce the number of if-else statements in your code, making it more readable and efficient.

1. Use Dictionaries

One way to reduce the number of if-else statements is to use dictionaries. You can use a dictionary to map different conditions to their corresponding actions. This way, you only need to check the dictionary once, rather than using multiple if-else statements.

def check_condition(condition):
    actions = {
        "condition1": action1,
        "condition2": action2,
        "condition3": action3,
    }
    action = actions.get(condition)
    if action:
        action()
    else:
        print("Invalid condition")

2. Use the Elif Statement

Another way to reduce the number of if-else statements is to use the elif condition. The elif condition allows you to check multiple conditions without using multiple if-else statements.

def check_condition(condition):
    if condition == "condition1":
        action1()
    elif condition == "condition2":
        action2()
    elif condition == "condition3":
        action3()
    else:
        print("Invalid condition")

3. Use the Switch Case Statement

In Python version before 3.10, there is no built-in switch case statement, but you can use a function or a class to mimic the behavior of the switch case.

class Switch:
    def __init__(self, value):
        self.value = value
        self.fall = False

    def __iter__(self):
        """Return the match method once, then stop"""
        yield self.match
        raise StopIteration

    def match(self, *args):
        """Indicate whether or not to enter a case suite"""
        if self.fall or not args:
            return True
        elif self.value in args:
            self.fall = True
            return True
        else:
            return False

def check_condition(condition):
    for case in Switch(condition):
        if case("condition1"):
            action1()
            break
        if case("condition2"):
            action2()
            break
        if case("condition3"):
            action3()
            break
        if case():
            print("Invalid condition")

Conclusion

Reducing the number of if-else statements in your code can make it more readable and efficient. By using dictionaries, the elif condition, or the switch case condition, you can reduce the number of if-else statements and make your code more manageable. Try out these approaches in your next project and see how they improve your code.

How to Reduce Multiple If-Else Statements in Python