python - How to check if an input matches a set of desired values without repeating myself? -


this question has answer here:

i want able this, inputs of 1, "d" or "dog" call do_something(), whereas other input call do_something_else().

command = input("type command") if command == (1 or "d" or "dog"):    do_something() else:     do_something_else() 

currently, not work, because python evaluating truthiness of (1 or "d" or "dog"), true, of course. then, since command true string, do_something called.

i know how 1 way: if command == 1 or command = "d" or command = "dog". works fine; however, involves lot of repetition, , i'm sure there must way shorten that.

i suppose make list of valid commands, valid_commands = [1,"d","dog"] , check if command in valid_commands, seems workaround, rather ideal approach.

you should use in operator:

command = input("type command") if command in ["1","d","dog"]:    do_something() else:    do_something_else()  

Comments

Popular posts from this blog

c++ - llvm function pass ReplaceInstWithInst malloc -

java.lang.NoClassDefFoundError When Creating New Android Project -

Decoding a Python 2 `tempfile` with python-future -