This question already has an answer here:
- Replacements for switch statement in Python? 33 answers
I know there are a lot of questions about that, but they are all about some specific cases.
I have a general question. I have code which compares user input to many possible values (keywords).
All works, but I hate the "monstrosity".
it's like this:
if userinput == "input1":
print('input1')
elif userinput == "input2":
print('input2')
elif userinput == "input3":
print('input3')
elif userinput == "input3":
print('input3')
elif userinput == "input3":
print('input3')
# repeat many times until the last else
else:
print('all the rest')
- the inputs can be ANYTHING. And comparison is not always just
==
. - the action on match sometimes can be a long piece of code too, not just print.
I can't really combine those conditions and I on purpose don't want to, since each one detects it's own thing.
My question is: Any practice of making such cases more readable? Cleaner?
One thing I am thinking is to call an external functions per case from each comparison and store those functions in separate *.py file. The best I can think of at this point..
Any better ideas\ways to handle that?
Aucun commentaire:
Enregistrer un commentaire