More than a few conditions

is there any easy way to write more conditions into my python scripts without writing if/else parts?

Let set like 30 conditions I want program to check and then do various things depends on those conditions.

I mean, I don't want to make something like this:

if X:

elif Y:

elif Z:

elif:

May I use dictionary for that or any other structure? Thank you for any help.


Solution 1:

There is a way by using a function dictionary.

Here is an example.

def funA():
    print("This is fun")

def funB():
    print("This is also fun")

def funC():
    print("Okay this is not fun anymore")

def funD():
    print("Why am I even here")

def main():
    func = {
    "Condition A": funA,
    "Condition B": funB,
    "Condition C": funC,
    "Condition D": funD,
    }
    while True:
        try:
            func[input("Input a condition: ")]()
        except KeyError:
            print("Bad choice, please type one of these:")
            for key in func:
                print(key)

if __name__ == "__main__":
    main()