eternity
eternity

Reputation: 1

Multiple Nested if Python

user_input_1 = string(input(“Y/N”))
user_input_2 = string(input(“Y/N”)
...
user_input_10 = string(input(“Y/N”))

Assuming that for each combination of inputs the code has to do another calculation, how do you avoid multiple if-elif-else?

For example:

if user_input_1 == “Y”:
    if user_input_2 == “Y”:
        if user_input_3 == “Y”:
            do_this()
                ...
    elif user_input_2 == “N”:
        do_that()
            ...
elif user_input_1 == “N”:
    ...
....

Going this way does not seem effective, because I will end up with hundreds of ifs

Upvotes: 0

Views: 54

Answers (1)

ZdaR
ZdaR

Reputation: 22954

I think a better way of representing such logical structure would be nested-dictionary. It can be written as:

def perform_action_on_user_input(ui1, ui2, ui3)
    decision_tree = {
        "Y": {
            "Y": {
                "Y": {do_yyy},
                "N": {do_yyn}
            },
            "N": {
                "Y": {do_yny},
                "N": {do_ynn}}
        },
        "N": {
            "Y": {
                "Y": {do_nyy},
                "N": {do_nyn}
            },
        }
    }

    if ui1 not in ["Y", "N"]:
        return "Invalid Input 1"
    if ui2 not in ["Y", "N"]:
        return "Invalid Input 2"
    if ui3 not in ["Y", "N"]:
        return "Invalid Input 3"
    
    return decision_tree[ui1][ui2][ui3]

method = perform_action_on_user_input(user_input_1, user_input_2, user_input_3)
print(method(*args)) # Call the respective method with required arguments
# It is possible that different method calls require different arguments, 
# then you will need to check the instance of `method` returned from 
# this method before passing in the args.

Upvotes: 1

Related Questions