python - How to check if an input matches a set of desired values without repeating myself? -
this question has answer here:
- how test 1 variable against multiple values? 16 answers
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
Post a Comment