0
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

2
  • suggestion: dont type out the question on a smartphone (iphone). The quotes become angular , which is actually invalid in python code. Commented Oct 21, 2022 at 16:00
  • I question whether you need 10 different values defined up front. Do you really have different paths to take for all 1,024 combinations of the 10 variables? Commented Oct 21, 2022 at 16:04

1 Answer 1

1

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.
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.