0

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 == "input4":
   print('input4')
 elif userinput == "input5":
   print('input5')
 # 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?

GeekSince1982
  • 732
  • 10
  • 25
  • Did you mean to have an elif for "input3" 3 times? – RCA Jun 29 '16 at 21:43
  • I sometimes put the then thing I'm matching on as a key in a dictionary and the thing I want to do as the value, then do something like `D[userinput]()` but that only works for `==` matches and a default – cmd Jun 29 '16 at 21:43

0 Answers0